标签:
Reverse a linked list.
For linked list 1->2->3
, the reversed linked list is 3->2->1
分析:
需要创建3个指针,然后就可以满足反转的要求。
1 /** 2 * Definition for ListNode. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int val) { 7 * this.val = val; 8 * this.next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param head: The head of linked list. 15 * @return: The new head of reversed linked list. 16 */ 17 public ListNode reverse(ListNode head) { 18 if (head == null) return head; 19 ListNode prev = null; 20 ListNode cur = head; 21 ListNode next = null; 22 while (cur != null) { 23 next = cur.next; 24 cur.next = prev; 25 prev = cur; 26 cur = next; 27 } 28 return prev; 29 } 30 }
转载请注明出处:cnblogs.com/beiyeqingteng/
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5635102.html