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

Reverse Linked List

时间:2016-07-02 13:07:48      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

Reverse a linked list.

Example

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/

 

Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/beiyeqingteng/p/5635102.html

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