反转一个链表。递归算法
原创
©著作权归作者所有:来自51CTO博客作者autumn的原创作品,请联系作者获取转载授权,否则将追究法律责任
// ReverseList.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
struct node{
int m_num;
struct node* pnext;
node(int num)
{
m_num=num;
pnext=NULL;
}
};
node* reverse(node* head)
{
static node* new_head;
if(head==NULL)
return NULL;
if(head->pnext !=NULL)
{
reverse(head->pnext);
head->pnext->pnext=head;
head->pnext=NULL;
}
else
new_head=head;
return new_head;
}
void travel(node* head)
{
node* pwalker=head;
while(pwalker!=NULL)
{
printf("%3d",pwalker->m_num);
pwalker=pwalker->pnext;
}
printf("\n");
}
int main(int argc, char* argv[])
{
node* head1=new node(1);
node* node2=new node(2);
node* node3=new node(3);
head1->pnext=node2;
node2->pnext=node3;
travel(head1);
node* rev=reverse(head1);
travel(rev);
printf("Hello World!\n");
return 0;
}
/*
1 2 3
3 2 1
Hello World!
Press any key to continue
*/
链表反序:
struct student *Reverse(struct student *head)
{
struct student *p; /*临时存储*/
struct student *p1; /*存储返回结果*/
struct student *p2; /*源结果节点一个一个取*/
p1 = NULL; /*开始颠倒时,已颠倒的部分为空*/
p2 = head; /*p2指向链表的头节点*/
while (p2 != NULL)
{
p = p2-> next;
p2-> next = p1;
p1 = p2;
p2 = p;
}
head = p1;
return head;
}