现在的位置: 首页 > 综合 > 正文

反转一个链表。递归算法

2013年03月12日 ⁄ 综合 ⁄ 共 1074字 ⁄ 字号 评论关闭
// 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; 

抱歉!评论已关闭.