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

【100题】第二十四 反转链表

2013年10月12日 ⁄ 综合 ⁄ 共 918字 ⁄ 字号 评论关闭

题目:新建一个链表,然后反转一下

#include <iostream.h>
#include <malloc.h>
using namespace std;

struct node
{
	int data;
	node *next;
};
void insert(node *root,node *p)
{
	p->next=root->next;
	root->next=p;
}
node *create(int a[],int n)
{
	node *root=(node *)malloc(sizeof(node));
	root->data=a[0];
	root->next=NULL;
	for(int i=1;i<5;++i)
    {
	   node *p = (node *)malloc(sizeof(node));
	   p->data=a[i];
	   p->next=NULL;
	   insert(root,p);
    }
	
	return root;
}
node  *reverse(node *root)
{
	
	node *head=root;
	node *p;
	node *q;
	
	if(head)
	  p=head->next;
    else 
       return head;
	while(p!=NULL)
	{
		q=p->next;
		p->next=head;
		
		head=p;
		p=q;

	}
	
	return head;
}
int main()
{
	node *root;
	int a[5]={2,3,4,5,6};
	root =create(a,5);
	
	node *temp1=root;
	for(int i=0;i<5;++i)
    {
	   cout<<temp1->data<<endl;
	   temp1=temp1->next;
    }
    
    node *reverseHead=reverse(root);
    cout<<"After reverse:"<<endl;
	node *temp2=reverseHead;
    for(int i=0;i<5;++i)
    {
	   cout<<temp2->data<<endl;
	   temp2=temp2->next;
    }
}

注意:新建链表的时候,切记一定要把节点node的所有元素都指明,例如node 有data、next 不要只初始化data而忘记p->next=NULL;

           如果忘记p->next=NULL;则在以后while(p)时候会停不下来

【上篇】
【下篇】

抱歉!评论已关闭.