链表创建、反转

#include<stdio.h>
#include<iostream>
// 定义链表结点
using namespace std;
typedef struct node{
    node *next;
    int data;
}*pnode;
//初始化结点
pnode initialnode(int  n){
    pnode head = (pnode)malloc(sizeof(node));
    if(head == NULL){
        cout<<"分配失败";
        exit(1);
    }
    pnode p = head,q;
    for (int i = 2; i <= n; i++){
        cin>>p->data;
        q = (pnode)malloc(sizeof(node));
        p->next = q;
        p = q;
    }
    cin>>p->data;
    p->next=NULL;
    return head;
}
//打印结点
void printnode(pnode head){
    if (head == NULL)
        cout<<"empty linknode"<<endl;
    else{
        pnode p=head;
        while(p != NULL){
            printf("%d->",p->data);
            p = p->next;
        }
    cout<<"NULL"<<endl;
    }
}
//链表反转
pnode reversenode( pnode head){
    pnode p,q,l; // l为中间结点,p反转前结点指针,q为反转后结点指针,通过l把p和q联系起来
    q=p=l=head;  
    p=p->next;
    q->next=NULL;
    while(p != NULL){
        l=p;
        p = p->next;
        l->next = q;
        q = l;
    }
    head = q;
    return head;
}
int main(){
    int n;
    scanf("%d",&n);
    pnode head;
    head=initialnode(n); //
    printnode(head);
    head=reversenode(head);
    printnode(head);
    free(head); //释放结点
    return 0;
}

// 有关链表操作,持续更新中

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值