Reverse linked list
Reverse a linked list.
ExampleFor linked list 1->2->3
, the reversed linked list is 3->2->1
Reverse a linked list.
For linked list 1->2->3
, the reversed linked list is 3->2->1
分析
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * 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 if (head == null ) return null ; ListNode last = null ; while (head.next != null ){ ListNode tmp = head.next; head.next = last; last = head; head = tmp; } head.next = last; return head; } } |