反转链表

#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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值