给定两个升序排列的单向链表 a、 b ,请设计一个方法合并 a和 b 且合并后保持降序有序。
例如: a : 5->10->15->20; b: 6->7->25
合并后为: 25->20->15->10->7->6->5
public static void mergeList(Node a,Node b){ Stack<Integer> merged=new Stack<>(); Node p=a,q=b; while(p!=null&&q!=null){ if(p.value<q.value){ merged.push(p.value); p=p.next; } if(q.value<p.value){ merged.push(q.value); q=q.next; } } while(p != null){ merged.push(p.value); p=p.next; } while(q!=null){ merged.push(q.value); q=q.next; } Node head=new Node(); head.setValue(merged.pop()); head.setNext(null); Node temp=head; while(!merged.isEmpty()){ Node t=new Node(); t.setNext(null); t.setValue(merged.pop()); temp.setNext(t); temp=t; } }
package algorithm; public class ConvertLink { private static class Node { int value; Node next; } private static void print(Node node) { while (node != null) { System.out.println(node.value); node = node.next; } } /** * 链表反转 * @param node * @return */ private static Node convertLink(Node node) { if (node == null || node.next == null) { return node; } Node preNode = node; Node editNode = node.next; Node nextNode = editNode.next; //循环开始之前必须要先把原来链表的头的next置为空,因为这个节点将是新链表的尾节点 preNode.next = null; while (editNode != null) { editNode.next = preNode; preNode = editNode; editNode = nextNode; if (nextNode != null) { nextNode = nextNode.next; } } return preNode; } /** * 传入两个链表都是降序排列 * * @param node1 * @param node2 * @return */ private static Node mergeTwoLink(Node node1, Node node2) { Node nextNode;//先将下一个节点保存起来 Node insertNode; Node editNode = node1; Node headNode = node1; //先判断头节点那个大 if (node1.value > node2.value) { insertNode = node2; }else{ insertNode = node2.next; node2.next = node1; headNode = node2; editNode = node2; } while (insertNode != null) { nextNode = insertNode.next; while (editNode != null && editNode.next != null && editNode.next.value > insertNode.value) editNode = editNode.next; Node editNextNode = editNode.next; editNode.next = insertNode; insertNode.next = editNextNode; insertNode = nextNode; } return headNode; } public static void main(String[] args) { Node head = new Node(); Node next1 = new Node(); Node next2 = new Node(); Node next3 = new Node(); Node next4 = new Node(); head.value = 5; head.next = next1; next1.value = 10; next1.next = next2; next2.value = 15; next2.next = next3; next3.value = 20; next3.next = next4; next4.value = 25; next4.next = null; Node head1 = new Node(); Node next21 = new Node(); Node next22 = new Node(); head1.value = 2; head1.next = next21; next21.value = 4; next21.next = next22; next22.value = 8; next22.next = null; System.out.println("convert before "); System.out.println("node 1"); print(head); System.out.println("node 2"); print(head1); head = convertLink(head); head1 = convertLink(head1); head = mergeTwoLink(head1,head); System.out.println("convert after"); print(head); } }