链表创建、反转

来源:互联网 发布:淘宝一元起拍靠谱吗 编辑:程序博客网 时间:2024/06/02 09:08
#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;}

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

0 0
原创粉丝点击