您的位置:首页 > 其它

Reverse Linked List

2015-06-08 23:21 375 查看
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(递推)

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *prev = head, *cur = head->next, *next = cur->next;
head->next = NULL;
while (next != NULL) {
cur->next = prev;
prev = cur;
cur = next;
next = next->next;
}
cur->next = prev;
return cur;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: