剑指offer 16题 【代码的鲁棒性】反转链表

题目描述

输入一个链表,反转链表。
牛客地址: http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

/**
 * 16.反转链表
 *
 */
public class Title16 {
	/**
	 * 书中代码
	 */
	public ListNode ReverseList(ListNode head) {
		
		ListNode before = null,cur = head, next = null,retNode = null;
		
		while(cur != null){
			next = cur.next;
			if(next == null)
				retNode = cur;
			
		    cur.next = before;
		    before = cur;
		    cur = next;
		}
		return retNode;
    	}
	
	/**
	 * 自己写的代码
	 */
	public ListNode ReverseList(ListNode head) {
		if(head == null)
			return null;
		ListNode before = null,cur = head, next = cur.next;
		
		while(next != null){
			cur.next = before;
			before = cur;
			cur = next;
			next = cur.next;
		}
		cur.next = before; // 这里注意
		return cur;
   	}
	
	public static void main(String[] args) {
		ListNode a = new ListNode(1);
		ListNode b = new ListNode(2);
		ListNode c = new ListNode(3);
		ListNode d = new ListNode(4);
		a.next =b;
		b.next =c;
		c.next = d;
		d.next = null;
		
		ListNode head = new Title16().ReverseList(a);
		while(head != null){
			System.out.print(head.val + " ");
			head = head.next;
		}
	}
}

以前写的代码
/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode *p,*pre,*last;
        p=last=pHead;
        pre=NULL;
         
        while(p != NULL){
            last=p->next;
            p->next=pre;
             
            pre=p;
            p=last;
        }
        return pre;
    }
};


你可能感兴趣的:(剑指offer)