剑指Offer_编程题_合并两个排序的链表
题目描述
输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。
题目答案,思路
https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337?f=discussion
递归版本
链接:https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337?f=discussion 来源:牛客网 public ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null){ return list2; } if(list2 == null){ return list1; } if(list1.val <= list2.val){ list1.next = Merge(list1.next, list2); return list1; }else{ list2.next = Merge(list1, list2.next); return list2; } }
非递归版本
public class Solution { public ListNode Merge(ListNode list1,ListNode list2) { ListNode root = new ListNode(-1); //临时指向的节点,可以理解为临时的 root 尾节点 ListNode last = root; while (list1 != null && list2 != null) { if (list1.val <= list2.val) { //重新 last.next=list1; last = list1; list1 = list1.next; } else { last.next = list2; last = list2; list2 = list2.next; } } //把未结束的链表连接到合并后的链表尾部 if (list1 != null) { last.next = list1; } if (list2 != null) { last.next = list2; } return root.next; } }
测试代码
public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class TestListNode { // 链接:https://www.nowcoder.com/questionTerminal/d8b6b4358f774294a89de2a6ac4d9337?f=discussion // 来源:牛客网 //尾插法创建单链表 队列形式先进先出 public void back(ListNode node, int data) { if (data < 10) { ListNode next = new ListNode(data); next.val = data; next.next = null; node.next = next; back(next,data+3); } } public void back2(ListNode node, int data) { if (data < 10) { ListNode next = new ListNode(data); next.next = null; node.next = next; back2(next, data=data+2); } } public static void main(String[] args) { ListNode headNode; ListNode headNode2; TestListNode list1 = new TestListNode(); headNode = new ListNode(3);//头指针 list1.back(headNode, 4);//后插法 System.out.println("创建后的链表是:"); // while (headNode.next != null) { // headNode = headNode.next; // System.out.print(headNode.val + " "); // } System.out.println("-----------------------------"); TestListNode list2 = new TestListNode(); headNode2 = new ListNode(4);//头指针 list2.back2(headNode2, 5);//后插法 System.out.println("创建后的链表是:"); // while (headNode2.next != null) { // headNode2 = headNode2.next; // System.out.print(headNode2.val + " "); // } ListNode merged= new Solution().Merge(headNode,headNode2); System.out.println("merge :"); while (merged.next != null) { merged = merged.next; System.out.print(merged.val + " "); } } }