合并两个有序链表

来源:互联网 发布:win10打不开任何软件 编辑:程序博客网 时间:2024/06/11 08:45

链表的基本构造:

public class ListNode {public int val;public ListNode next;public ListNode(int val, ListNode next) {super();this.val = val;this.next = next;}public ListNode(int val) {super();this.val = val;}public static ListNode arrayToList(int[] arr) {ListNode head = new ListNode(0);ListNode p = head;for(int value : arr){p.next = new ListNode(value);p = p.next;}return head.next;}public static void printList(ListNode head){ListNode p = head;while(p != null){System.out.print(p.val + " ");p = p.next;}System.out.println();}}

2.两个链表的合并代码:

public class 合并两个有序链表 {public static void main(String[] args) {int[] array1 = { 1, 3, 7, 8 };ListNode head1 = ListNode.arrayToList(array1);ListNode.printList(head1);int[] array2 = { 2, 4, 5, 9 };ListNode head2 = ListNode.arrayToList(array2);ListNode.printList(head2);ListNode.printList(mergeList(head1, head2));}private static ListNode mergeList(ListNode head1, ListNode head2) {if (head1 == null && head2 == null) {return null; // 如果两个链表都为空}if (head1 == null) {return head2;}if (head2 == null) {return head1;}/** * 新链表的头结点 一开始,我们让current结点指向head1和head2中较小的数据,得到head结点 */ListNode head;ListNode current;if (head1.val < head2.val) {head = head1;current = head1;head1 = head1.next;} else {head = head2;current = head2;head2 = head2.next;}while (head1 != null && head2 != null) {if (head1.val < head2.val) {current.next = head1; // 新链表中,current指针的下一个结点对应较小的那个数据current = current.next; // current指针下移head1 = head1.next;} else {current.next = head2;current = current.next;head2 = head2.next;}}// 合并剩余的元素if (head1 != null) {current.next = head1;}if (head2 != null) {current.next = head2;}return head;}}


原创粉丝点击