#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;
}
07-20
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交