反转链表

来源:互联网 发布:阿里云 网站端口 编辑:程序博客网 时间:2024/06/05 16:14
#include <iostream>#include <cstdio>using namespace std;class node{public:    int data;    node * next;    node(int d):data(d),next(NULL)    {    }    node(){}};void add(node * &head,node * &tail,int data){    node * s = new node(data);    if(head==NULL)    {        head=s;        tail=s;    }    else    {        tail->next=s;        tail=s;    }}void reverses(node *& head){    node *p, *q, *tmp;   //坑爹,注意指针定义不要漏写*    //tail=head;    p=head;    q=head->next;    head->next=NULL;     //这句忘了也好坑爹。因为遍历的时候需要终止。    while(q!=NULL)    {        tmp=q->next;   //先找到中间点的下一个节点,tmp记录。否则中间点的next改变后找不到下一个节点        q->next=p;     //中间点-》next指向前一个节点。        p=q;        q=tmp;    }    head=p;}void output(node * head){    while(head->next!=NULL)    {        cout<<head->data<<" ";        head=head->next;    }    cout<<head->data<<endl;}int main(){    node * head=NULL;    node * tail=NULL;    int data;    //freopen("in.txt","r",stdin);    while(cin>>data&&data!=-1)    {        add(head,tail,data);    }    reverses(head);    output(head);}

0 0