c++翻转链表


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <stack>
#include <queue>
#include <algorithm>
using  namespace std;
#define CLS(x,v)  memset(x,v,sizeof(x))
#define LL long long
#define M 50001


struct Node
{
    int data;
    Node *next;
};

Node* create(int n){
    if(n<1)return NULL;
     Node* p=new Node;// 返回类型是Node *
     p->data=1;
    Node *head=p;
    Node *temp;
    for(int i=2;i<=n;i++)
    {
        temp=new Node;
        temp->data=i;
        p->next=temp;
        p=temp;
    }
    p->next=NULL;
    return head;
}
//反转链表效率O(n)
Node* myreverse(Node* head)
{
    Node *one,*two,*three;
    //初始化第一 二个
    one=head;if(one==NULL)return NULL;//链表长度为0
    two=one->next;if(two==NULL)return one;//链表长度为1
    one->next=NULL;
    while(1)
    {
        //根据地第二个产生第三个
        three=two->next;
        two->next=one;
        if(three==NULL)break;
        //前移 第一、二个指针
        one=two;
        two=three;
    }
    return two;
}
//查看链表
void show(Node *p)
{
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}
//释放链表
void myfree(Node *p){
    Node *temp;
    while(p!=NULL)
    {
        temp=p->next;
        delete p;
        p=temp;
    }
}
int main()
{
    Node* head=create(5);
    show(head);
    //
    head=myreverse(head);
    show(head);
    //
    myfree(head);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值