反转链表(递归和迭代两种实现)

 1 #define IO std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
 2 #define bug(x) cout<<#x<<" is "<<x<<endl;
 3 #include<bits/stdc++.h>
 4 using namespace std;
 5 typedef long long ll;
 6 struct Node{
 7     int x;
 8     Node*next;
 9     Node(int x1,Node *next1){
10         x=x1,next=next1;
11     }
12 };
13 void reverse(Node *&head){
14     if(!head||!head->next)return;
15     Node *p=head;
16     Node *cur=nullptr;
17     while(p){
18         Node *q=p->next;
19         p->next=cur;
20         cur=p;
21         p=q;
22     }
23     head=cur;
24 }
25 Node* reverse1(Node *&pre,Node *&p){
26     if(!p->next){
27         p->next=pre;
28         return p;
29     }
30     Node *q=p->next;
31     p->next=pre;
32     pre=p;
33     return reverse1(pre,q);
34 } 
35 void print(Node *head){
36     while(head){
37         cout<<head->x<<" ";
38         head=head->next;
39     }
40     cout<<endl;
41 }
42 int main(){
43     Node *head=new Node(1,nullptr);
44     Node *pre=head;
45     for(int i=2;i<=5;i++){
46         Node *p=new Node(i,nullptr);
47         pre->next=p;
48         pre=p;
49     }
50     print(head);
51     reverse(head);
52     print(head);
53     Node *p=nullptr;
54     head=reverse1(p,head);
55     print(head);
56     p=nullptr;
57     head=reverse1(p,head);
58     print(head);
59 }

 

posted @ 2024-06-03 14:45  Venux  阅读(2)  评论(0编辑  收藏  举报