剑指offer之链表续

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

这道题用递归,很容易实现,但是一定要注意代码鲁棒性

下面是源码:

public static ListNode MergeList(ListNode head1,ListNode head2){
		ListNode newHead = null;
		if(head1==null){
			return head2;
		}
		else{
			if(head2==null){
				return head1;
			}
		}
		if(head1.val<head2.val){
			newHead = head1;
			newHead.next = MergeList(head1.next,head2);
		}
		if(head1.val>head2.val){
			newHead = head2;
			newHead.next = MergeList(head1,head2.next);
		}
		return newHead;
	}

  通过这道题想到如果是有序数组的话,该如何合并,这里不能用递归,主要是因为数组长度的问题

可以借鉴剑指offer第4题,替换空格。源码就不赋了,之前的博客中有提到过。

面试题15:链表中的倒数第K 个结点

当一个指针无法解决问题的时候,考虑尝试两个或三个指针,同样求链表的中间结点以及判断单向链表是否有环都可以考虑使用两个指针。

这道题可以考虑两个指针,一个在前,另一个在他K-1的位置,但是要注意如果k 为0,头结点为空,或者链表长度小于K,这些情况

下面附上程序的源代码:

public static ListNode findKNode(ListNode head, int k){
		if(head==null||k == 0){
			return null;
		}
		ListNode p1 = head;
		ListNode p2 = head;
		for(int i =0;i<k-1;i++){
			if(p1.next!=null){
				p1 = p1.next;
			}
			else{
				return null;
			}
		}
		while(p1.next!=null){
			p1 = p1.next;
			p2 = p2.next;
		}
		return p2;
	}

 面试题16:翻转链表

 这道题用到了三个指针,只要保证翻转的时候链表不断就可以.

这道题也是leetcode上top10的题目;

Reverse Linked List

 Reverse a singly linked list.

下面附上代码:

public ListNode reverseList(ListNode head) {
        ListNode n = head;
        ListNode l = null;
        ListNode r = null;
        ListNode newHead = null;
        while(n!=null){
        	r = n.next;
        	if(r==null){
        		newHead = n;
        	}
        	n.next = l;
        	l = n;
        	n = r;
        }
        return newHead;
    }

  

 

posted @ 2015-06-03 16:10  niuer++  阅读(179)  评论(0)    收藏  举报