A single linked list can be reversed by using a loop, or by using a recursive method
1. Cycle reversal single linked list
In the loop method, use the pre to point to the previous node, Cur point to the current node, each time pointing the Cur->next to the pre.
Code:
# include <iostream>
# include <cstdlib>
using namespace std;
struct Linknode
{
int val;
Linknode *next;
Linknode (int x): Val (x), Next (NULL) {}
};
Linknode *reverse2 (Linknode *head)
{
if (head==null) return
NULL;
Linknode *pre=null;
Linknode *p=head;
Linknode *h=null;
while (p)
{
h=p;
Linknode *tmp=p->next;
p->next=pre;
pre=p;
p=tmp;
}
return h; Return header node
int main () //test code
{
Linknode *head=new linknode (1);
Linknode *p1=new Linknode (2);
Linknode *p2=new Linknode (3);
head->next=p1;
p1->next=p2; Establish the chain list 1->2->3->null
linknode *p=reverse2 (head);
while (p)
{
cout<<p->val<<endl;
p=p->next;
} Output is 3->2->1->null
system ("pause");
return 0;
}
2. Recursive implementation of single linked list inversion
# include <iostream>
# include <cstdlib>
using namespace std;
struct Linknode
{
int val;
Linknode *next;
Linknode (int x): Val (x), Next (NULL) {}
};
Linknode *reverse (Linknode *head,linknode * &newhead) //head is the head node of the original linked list, Newhead is the head node of the new list
{
if (head== NULL) return
null;
if (head->next==null)
{
newhead=head;
}
else
{
reverse (head->next,newhead);
head->next->next=head;
head->next=null;
}
return newhead;
}
int main () //test code
{
Linknode *head=new linknode (1);
Linknode *p1=new Linknode (2);
Linknode *p2=new Linknode (3);
head->next=p1;
p1->next=p2; Set up a list 1->2->3->null;
Linknode *newhead=null;
Linknode *p=reverse (head,newhead);
while (p)
{
cout<<p->val<<endl;
p=p->next;
} Output Chain list 3->2->1->null;
System ("pause");
return 0;
}