Reverse Linked List

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 };

 

posted @ 2015-06-08 23:21  huj690  阅读(297)  评论(0编辑  收藏  举报