面试题17:合并两个排序的链表

题目:

//输入两个递增排序链表,合并这两个链表并使新链表中的节点仍然是按照递增的顺序。

ListNode类(结点类)

 1 package leetcode.utilities;

 2 

 3 public class ListNode {

 4     public int    val ;

 5     public ListNode   next ;

 6     public ListNode(int val) {

 7         // TODO Auto-generated constructor stub

 8         this.val = val;

 9         this.next = null ;    

10     }    

11     //打印链表

12         public static void PrintList(ListNode head){

13             System.out.println("PrinyList  start");

14             ListNode pNode = head ;

15             System.out.print("{ ");

16             while(pNode != null){

17                 System.out.print(pNode.val + " ");

18                 pNode= pNode.next;

19             }

20             System.out.println(" }");

21         }

22 }

 

 

递归实现Java代码:

 1 package com.hb.jzoffer;

 2 

 3 import leetcode.utilities.ListNode;

 4 //面试题17:合并两个排序的链表

 5 public class MergeSortedLists {

 6     public ListNode merge(ListNode pHead1 , ListNode  pHead2){

 7         //判断两个链表是否为空

 8         if(pHead1 == null ){

 9             return pHead2;

10         }else if(pHead2 == null ){

11             return  pHead1;

12         }

13         

14         ListNode  pMergedHead = null;

15         

16         //递归调用

17         if(pHead1.val < pHead2.val){

18             pMergedHead = pHead1 ;

19             //下面递归调用自己,返回的值是pMergedHead后面的节点,一直到递归结束,才会返回pMergedHead新的头结点。

20             pMergedHead.next = merge(pHead1.next, pHead2) ;  

21         }else{

22             pMergedHead = pHead2 ;

23             pMergedHead.next = merge(pHead1, pHead2.next);

24         }

25         

26         return pMergedHead ;        

27     }

28     

29     public static void main(String[] args) {

30         ListNode head1 = new ListNode(1);

31         ListNode n1 = new ListNode(3);

32         ListNode n2 = new ListNode(5);

33         ListNode n3 = new ListNode(7);

34         ListNode n4 = new ListNode(9);

35         

36         head1.next = n1 ;

37         n1.next = n2 ;

38         n2.next = n3 ;

39         n3.next = n4 ;

40         

41         ListNode head2 = new ListNode(2);

42         ListNode n5 = new ListNode(4);

43         ListNode n6 = new ListNode(6);

44         

45         head2.next = n5 ;

46         n5.next = n6;

47         

48         MergeSortedLists  merge = new MergeSortedLists();

49     

50         ListNode  mergeHead = merge.merge(head1, head2);

51         

52         ListNode.PrintList(mergeHead);        

53         

54     }

55 }

 

个人理解错误的地方:

  对递归函数理解不深入,容易想当然的把返回值错误的理解了。

 //下面递归调用自己,返回的值是pMergedHead后面的节点,一直到递归结束,才会返回pMergedHead新的头结点。

  该方法一直在调用自己,只有当不调用的时候,才会最后返回新的头结点。

你可能感兴趣的:(面试题)