鏈表創建、反轉

#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;
}

// 有關鏈表操作,持續更新中

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章