Solution 24: 链表翻转

程序 

public class ListReverse {
	public ListNode reverseList(ListNode head) {
		if (head == null) {
			return head;
		}

		ListNode pre = head;
		ListNode cur = pre.next;
		pre.next = null;

		while (cur != null) {
			ListNode next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}

		return pre;
	}
	
	public ListNode reverseList2(ListNode head) {
		ListNode pre = null;
		ListNode cur = head;
		
		while (cur!=null) {
			ListNode next = cur.next;
			cur.next = pre;
			pre = cur;
			cur = next;
		}
		
		return pre;
	}
}

 

第一种是比较常见,第二种更为简洁。

posted @ 2015-07-08 10:37  Chapter  阅读(132)  评论(0编辑  收藏  举报