#include<iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode(int x):val(x),next(NULL){}
};
//https://leetcode-cn.com/problems/reverse-linked-list/solution/die-dai-di-gui-jie-fa-by-sunshy/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head){
return nullptr;
}
ListNode *pre = head;
ListNode *cur = head->next;
while(cur !=nullptr){
pre->next = cur->next;
ListNode *tmp= cur->next;
cur->next = head;
head = cur;
cur = tmp;
}
return head;
}
};
int main(){
Solution so;
ListNode *l1 = new ListNode(1);
ListNode *l2 = new ListNode(2);
ListNode *l3 = new ListNode(3);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = l5;
ListNode *ll = so.reverseList(l1);
while(ll->next !=NULL){
cout << l1->val << ",";
l1 = l1->next;
}
}
//use stack
public static ListNode reverseListVersion2(ListNode head) {
if(head == null){
return null;
}
Stack<Integer> transferStack = new Stack<>();
ListNode pre = head;
while (pre.next!=null){
transferStack.push(pre.val);
pre = pre.next;
}
transferStack.push(pre.val);
ListNode dummpy = new ListNode(-1);
pre = dummpy;
while (transferStack.size()>0){
pre.next = new ListNode(transferStack.pop());
//新链表每加一个节点,当前指针就向前走一步
pre = pre.next;
}return dummpy.next;
}
no206 Reverse Linked List
最新推荐文章于 2022-10-17 16:52:17 发布
本文深入探讨了链表逆序算法的实现细节,通过迭代和递归两种方法,详细解释了如何反转链表。提供了完整的C++代码示例,并对比了使用栈进行逆序的替代方案。
772

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



