Reverse a singly linked list.
recursively
/**
* 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 || !head->next) return head;
ListNode* p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
iteratively
用了vector存下来。
/**
* 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 || !head->next) return head;
ListNode* p = head;
ListNode* q = new ListNode(0);
q->next = p;
vector<int> v;
while(head){
v.push_back(head->val);
head = head->next;
}
for(int i = v.size()-1; i>=0;--i){
p->val = v[i];
p = p->next;
}
return q->next;
}
};iteratively 直接改
/**
* 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* pre = NULL;
while(head){
ListNode* next = head->next; //先保存下来 不然下一条语句会改变
head->next = pre;
pre = head;
head = next;
}
return pre;
}
};
本文介绍了一种将单链表逆序的方法,包括递归和迭代两种实现方式。递归方法通过反转指针来实现链表逆序;迭代方法则通过三个指针前、中、后来逐个节点地修改节点指向,最终达到逆序效果。
419

被折叠的 条评论
为什么被折叠?



