首页 > 其他 > 详细

Reverse Linked List

时间:2015-06-09 00:37:30      阅读:226      评论:0      收藏:0      [点我收藏+]

Reverse a singly linked list.

思路:

to slove this problem, I choose a recurrent method, to reverse linked-list nodes one-by-one.

first, point head to NULL.(make the head be a tail)

and then, point cur node to prev node, and then, move prev pointer to cur node, move cur pointer to next node.

until next node move to NULL.

 

*recursive(递归),recurrent(递推)

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         if (head == NULL || head->next == NULL) {
13             return head;
14         }
15         ListNode *prev = head, *cur = head->next, *next = cur->next;
16         head->next = NULL;
17         while (next != NULL) {
18             cur->next = prev;
19             prev = cur;
20             cur = next;
21             next = next->next;
22         }
23         cur->next = prev;
24         return cur;
25     }
26 };

 

Reverse Linked List

原文:http://www.cnblogs.com/huj690/p/4562257.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!