[LeetCode] 206. Reverse Linked List
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: The new head of reversed linked list. */ public ListNode reverse(ListNode head) { // write your code here ListNode previous = null; while(head != null){ //Remember: assigne as circle ListNode temp = head.next; head.next = previous; previous = head; head = temp; } return previous; } }
最佳方法去记住list修改的顺序:这是一个循环,从temp开始,上一行等号右边就是下一行等号左边的。一直到循环结束。这个方法考虑了empty list以及只有一个node的list
下边也是一个思路,只是更容易理解而已。
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode prev = null; ListNode next = null; while (head != null) { next = head.next; head.next = prev; prev = head; head = next; } return prev; } }
posted on 2015-12-01 09:54 codingEskimo 阅读(100) 评论(0) 编辑 收藏 举报