标签:
Reverse a singly linked list.
Don‘t forget to consider the case where the linked list is empty
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode reverseList(ListNode head) { 11 if (head == null) return null; 12 ListNode dummy = new ListNode(-1); 13 dummy.next = head; 14 ListNode end = dummy; 15 while (end.next != null) { 16 end = end.next; 17 } 18 while (dummy.next != end) { 19 ListNode cur = dummy.next; 20 ListNode next = cur.next; 21 cur.next = end.next; 22 end.next = cur; 23 dummy.next = next; 24 } 25 return dummy.next; 26 } 27 }
标签:
原文地址:http://www.cnblogs.com/EdwardLiu/p/5047570.html