新增一个链表,然后分别采用2个指针指向这两个链表,每次比较链表的值,将较小的那一个存入新链表中。需要主要的是对空链表进行处理,主要还是考察代码的鲁棒性。总共2个链表,数组分别是1,3,5,7,和2, 4, 6,8
采用java进行实现。
package com.test.algorithm; class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } } public class Merge { public static ListNode Merge(ListNode list1,ListNode list2) { if(list1 == null && list2 == null) return null; if(list1 == null) return list2; if(list2 == null) return list1; ListNode newNode = new ListNode(0); ListNode tmp = new ListNode(0); tmp = newNode; if(list1.val < list2.val){ newNode.val = list1.val; list1 = list1.next; } else{ newNode.val = list2.val; list2 = list2.next; } //newNode.next = null; while(list1!=null && list2!=null){ if(list1.val < list2.val){ newNode.next = list1; newNode = newNode.next; newNode.val = list1.val; list1 = list1.next; }else{ newNode.next = list2; newNode = newNode.next; newNode.val = list2.val; list2 = list2.next; } } if(list1!=null){ newNode.next = list1; newNode = newNode.next; //list1 = list1.next; } if(list2!=null){ newNode.next = list2; newNode = newNode.next; //list2 = list2.next; } return tmp; } public static void main(String[] args) { ListNode list1 = new ListNode(1); ListNode list2 = new ListNode(2); list1.next = null; list2.next = null; ListNode head1 = list1; ListNode head2 = list2; for(int i = 2 ; i <=8 ; i ++){ if(i%2!=0) { ListNode temp = new ListNode(i); temp.next = list1.next; list1.next = temp; list1 = temp; } } for(int i = 4 ; i <=8 ; i ++){ if(i%2==0) { ListNode temp = new ListNode(i); temp.next = list2.next; list2.next = temp; list2 = temp; } } ListNode newNode = Merge(head1,head2); for(int i = 1 ; i <= 8 ; i++){ System.err.println(newNode.val); newNode = newNode.next; } } }