码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode: Reverse Linked List

时间:2015-12-15 12:24:48      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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 }

 

Leetcode: Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/EdwardLiu/p/5047570.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!