數據結構-----鏈表的逆序

鏈表的逆序,一般面試都喜歡整這個;已下提供一個省地方的程序;

#include <stdio.h>
#include <stdlib.h>


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


typedef struct node * LIST;
typedef struct node * NODE;
typedef struct node * POS;


int main(void)
{
    NODE n4 = (NODE)malloc(sizeof(struct node));
    n4->data = 'D',n4->next = NULL;
    NODE n3 = (NODE)malloc(sizeof(struct node));
    n3->data = 'C',n3->next = n4;
    NODE n2 = (NODE)malloc(sizeof(struct node));
    n2->data = 'B',n2->next = n3;
    NODE n1 = (NODE)malloc(sizeof(struct node));
    n1->data = 'A',n1->next = n2;


    POS handle = n1;
    for(;handle != NULL;handle = handle->next){
        printf("[%c] ",handle->data);
    }
    printf("\n");


    POS prev = NULL;
    POS cur  = n1;
    POS next = n1->next;
    while(cur){
        cur->next = prev;
        prev = cur;
        cur = next;
        if(next != NULL)
        next = cur->next;
    }


    handle = n4;
    for(;handle != NULL;handle = handle->next){
        printf("[%c] ",handle->data);
    }
    printf("\n");


    return 0;
}

發佈了25 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章