1. 程式人生 > >連結串列建立、反轉

連結串列建立、反轉

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

// 有關連結串列操作,持續更新中