首页 > 其他 > 详细

021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode

时间:2015-10-03 19:35:03      阅读:274      评论:0      收藏:0      [点我收藏+]

原题

  Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 

题目大意

  合并两个排序链表并返回一个新的列表。新的链表的结果由原先的两个链表结点组成,也就是不能合并后的链表不能包含新创建的结点。 

解题思路

  使用头结点root进行辅助操作,创建一个头结点,再使用两个引用指向两个链表的头结点,将较小的结点值的结点摘下来接到root链表的末尾,同时被摘的链头引用移动到下一个结点,一直操作,到到原先两个链表中有一个为空,最后再将剩下的结点接到root链表的末尾。最后返回root的下一个结点,其就为新的链表头。 

代码实现

//整体代码
import java.util.* ;

public class Demo04{
	
	public static ListNode mergeLists(ListNode l1,ListNode l2){
		ListNode head = new ListNode(0);
		ListNode p = head ;
		
		while(l1!=null&&l2!=null){
			if(l1.val<=l2.val){
				p.next = l1 ;
				l1 = l1.next ;
			}else {
				p.next = l2 ;
				l2 = l2.next ;
			}
			p = p.next ;	//移动到新的尾结点
		}
	
		p.next = (l1 != null ? l1 :l2 ) ;
		return head.next ;
	}
	//递归实现
	public static ListNode mergeRecursive(ListNode l1,ListNode l2){
		if(l1==null)return l2 ;
		if(l2==null)return l1 ;
		ListNode head = new ListNode(0);
		if(l1.val < l2.val){
			head = l1 ;
			head.next = mergeRecursive(l1.next,l2) ;
		}else{
			head = l2 ;
			head.next = mergeRecursive(l1,l2.next) ;
		}
		return head ;
	}
	
	public static void main(String args[]){
		ListNode l1 = new ListNode(0) ;
		ListNode l2 = new ListNode(0) ;
		ListNode p = l1 ;
		Scanner sin = new Scanner(System.in);
		int m = sin.nextInt();
		int n = sin.nextInt();
		for(int i=0;i<m;i++){
			int a = sin.nextInt();
			p.next = new ListNode(a);
			p = p.next ;
		}
		p = l2 ;
		for(int i=0;i<n;i++){
			int a = sin.nextInt();
			p.next = new ListNode(a);
			p = p.next ;
		}
		
		/*	错误代码:此处移动了l1、l2的指向,导致后续错误
		for(int i = 0;i<10;i++){
			System.out.print(l1.next.val+" ");
			l1 = l1.next;
		}
		System.out.println();
		for(int i = 0;i<10;i++){
			System.out.print(l2.next.val+" ");
			l2 = l2.next;
		}
		*/
		
		ListNode res = mergeRecursive(l1.next,l2.next);
		print(res);
		for(int i = 0;i<m+n;i++){
			System.out.print(res.val+" ");
			res = res.next;
		}
		System.out.println();
	}
	public static void print(ListNode head){
		while(head!=null){
			System.out.print(head.val+" ");
			head = head.next ;
		}
		System.out.println();
	}
}
class ListNode{
	int val ;
	ListNode next ;
	
	ListNode(int x){
		val = x ;
		next = null ;
	}
}


021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode

原文:http://my.oschina.net/damonzh/blog/513363

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!