Reverse a singly linked list.
常规方法,遍历一遍,迭代计算。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head)
{
if(NULL == head)
return NULL;
struct ListNode * p = head->next;
/*第一个结点的next置为NULL*/
head->next = NULL;
/*中间变量,用于保存当前处理节点的下一个节点*/
/*处理结束后赋值给p,开始下一次循环*/
struct ListNode *ptmp = NULL;
while(p)
{
/*保存当前处理结点的下一个节点*/
ptmp = p->next;
p->next = head;
head = p;
/*当前处理结点的下一个节点赋值给p*/
p = ptmp;
}
return head;
}
递归实现,gdb跟了下,自己知道大致思路,却总AC不了,参考大神的Java代码,编写如下递归形式的代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head)
{
if(NULL==head||NULL==head->next)
return head;
struct ListNode *p=head->next;
head->next=NULL;
struct ListNode *newhead = reverseList(p);
p->next=head;
return newhead;
}
另一种相对清晰的解法:
/**
* 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) {
ListNode *curr = head,*prev = NULL;
while(curr != NULL)
{
ListNode *temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
};
较好理解的递归实现:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
ListNode* node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return node;
}
};
C++迭代实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr,*curr = head;
while(curr)
{
ListNode* tmp = curr->next;
curr->next = prev;
prev = curr;
curr = tmp;
}
return prev;
}
};