链表反转C实现(递归与循环)

时间:2023-03-10 06:12:36
链表反转C实现(递归与循环)
 //逆转链表http://blog.163.com/lichunliang1988116@126/blog/static/26599443201282083655446/
#include<iostream.h>
#include<stdlib.h>
typedef struct Node
{
int data;
Node *next;
}*Linklist,ListNode;
void initLink(Linklist *head)
{ Node *node=(Node *)malloc(sizeof(Node));
node->data=;
node->next=NULL; head=&node; } void addNode(Linklist head,int no) {
Node *node=(Node *)malloc(sizeof(Node));
node->data=no;
node->next=NULL;
cout<<"加个数据为"<<no<<endl;
node->next=head->next;
head->next=node;
} void print(Linklist head)
{
Linklist current=head;
while(current!=NULL)
{
cout<<current->data<<" ";
current=current->next; }
cout<<endl; }
//recursive fanhui head function
Linklist recursive2(Linklist head,Linklist &newHead)
{
if(head->next==NULL)
{
newHead=head;
return head; }
Node *p1=head;
Node *p2; p2=recursive2(p1->next,newHead); p2->next=p1;
p1->next=NULL; } Linklist reverse1(Linklist head)
{
//if linklist is a node or null ,we need not inverse the linklist
if(head==NULL||head->next==NULL)
{
return head;
} Linklist pre=head;
Node *current=head->next;
Linklist next1=current->next;
//notice that head->next should be null;
head->next=NULL; while(next1!=NULL)
{
current->next=pre;
pre=current; current=next1; next1=next1->next; } current->next=pre; return current; } void main()
{
cout<<"你好"<<endl;
Linklist h=NULL;
h=(Node *)malloc(sizeof(Node));
h->data=;
h->next=NULL; addNode(h,);
addNode(h,);
addNode(h,);
cout<<"反转前"<<endl;
print(h);
h=reverse1(h);
print(h);
cout<<"revese again"<<endl;
recursive2(h,h);
print(h); }