您的位置:首页 > 其它

单链表逆序

2014-07-14 13:39 169 查看
非常简单,就当练个手吧

//单链表逆序问题,其实很容易的,就是把指针指向给变一下,注意的几个问题
//(1)如果就一个元素,不算头结点,直接返回
//(2)注意头结点最后要单独处理问题
#include <iostream>
using namespace std;

typedef struct linknode{
int val;
linknode * next;
}node,*list;                  //加typedef说明node和list是类型,否则只是一个struct的变量

void reverse(list head)
{
if(head==NULL||head->next==NULL||head->next->next==NULL)
return;
node * p=head->next;
node * q=p->next;
node * t;
p->next=NULL;
while(q!=NULL)
{
t=q->next;
q->next=p;
p=q;
q=t;
}
head->next=p;
}
list createlist()
{
int data;
list head=new node;
head->val=0;
head->next=NULL;
node * p=head;
while(cin>>data)
{
node * tmp=new node;
tmp->val=data;
tmp->next=NULL;
p->next=tmp;
p=tmp;
}
return head;
}

int main()
{
node * head=createlist();
reverse(head);
node *p=head->next;
while(p)
{
node *q=p->next;
cout<<p->val<<" ";
delete p;
p=q;
}
cout<<endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: