两个有序链表的合并
已知两个链表head1和head2各自有序,请把它们合并成一个依然有序的链表。结果链表要包含head1和head2的所有节点,及节点值相同。
1 package com; 2 class Node{ 3 Node next = null; 4 int data; 5 public Node(int data){ 6 this.data = data; 7 } 8 } 9 10 public class MergeList { 11 public static Node mergeList(Node head1, Node head2){ 12 if (head1 == null){ 13 return head1; 14 } 15 if (head2 == null){ 16 return head2; 17 } 18 Node p1 = null; // p1负责跟踪第一个链表的每个节点 19 Node p2 = null; // p2负责跟踪第二个链表的每个节点 20 Node head = null; // 新链表的头节点 21 if (head1.data < head2.data){ // 确定新链表的头 22 head = head1; 23 p1 = head1.next; 24 p2 = head2; 25 } else { 26 head = head2; 27 p1 = head1; 28 p2 = head2.next; 29 } 30 Node pcur = head; // pcur负责延长新链表 31 while (p1 != null && p2 != null) { 32 if (p1.data < p2.data) { 33 pcur.next = p1; 34 pcur = p1; 35 p1 = p1.next; 36 } else { 37 pcur.next = p2; 38 pcur = p2; 39 p2 = p2.next; 40 } 41 } 42 if (p1 != null){ // 当第二个链表遍历完但第一个链表没有遍历完时,将第一个链表剩余的节点接到新链表上。 43 pcur.next = p1; 44 } 45 if (p2 != null){ // 当第一个链表遍历完但第二个链表没有遍历完时,将第二个链表剩余的节点接到新链表上。 46 pcur.next = p2; 47 } 48 return head; 49 } 50 public static void main(String[] args){ 51 Node head1 = new Node(1); 52 Node node3 = new Node(3); 53 Node node5 = new Node(5); 54 head1.next = node3; 55 node3.next = node5; 56 node5.next = null; 57 Node head2 = new Node(2); 58 Node node4 = new Node(4); 59 Node node6 = new Node(6); 60 Node node7 = new Node(7); 61 head2.next = node4; 62 node4.next = node6; 63 node6.next = node7; 64 node7.next = null; 65 Node mergeHead = mergeList(head1, head2); 66 while (mergeHead != null){ 67 System.out.print(mergeHead.data + " "); 68 mergeHead = mergeHead.next; 69 } 70 } 71 }