對于鏈表,輸入輸出以及逆轉(zhuǎn)是比較常見的,輸入輸出時可以根據(jù)自己的需要調(diào)整,我這寫的c程序是輸入一個鏈表的長度,然后輸入鏈表各節(jié)點數(shù)據(jù),最后輸出順序的數(shù)據(jù)以及逆序的數(shù)據(jù)。給了三個函數(shù),分別是輸入輸出以及逆轉(zhuǎn)的程序。
先給出一個輸入輸出函數(shù):
#include<stdio.h>#include<stdlib.h>typedef struct node * List;struct node{ int data; List next;};List read(){ int len,num; List first,second,third; scanf("%d",&len); scanf("%d",&num); first=(List)malloc(sizeof(struct node)); first->data=num; first->next=NULL; second=first; len--; while(len--) { scanf("%d",&num); third=(List)malloc(sizeof(struct node)); third->data=num; third->next=NULL; second->next=third; second=third; } return first;}int main(){ List L1; L1=read(); while(L1->next!=NULL) { PRintf("%d ",L1->data); L1=L1->next; } printf("%d/n",L1->data); return 0;}
運行如圖。
單鏈表逆轉(zhuǎn)也和上面類似,多了一個逆轉(zhuǎn)過程:
#include <stdio.h> #include<stdlib.h>typedef int ElementType; typedef struct Node * PtrToNode;typedef PtrToNode List; struct Node { ElementType Data; PtrToNode Next; }; int main() { List Read(); void Print( List L ); List Reverse( List L ); //函數(shù)聲明 List L1, L2; L1 = Read(); Print(L1); L2 = Reverse(L1); //如果將這一行和上面一行交換位置,就會不一樣,輸出L1的時候就會只有一個數(shù)。 Print(L2); return 0; } List Read() { int len; int num; List list; List last; List node; scanf( "%d",&len ); if( len == 0 ) return NULL; scanf( "%d",&num ); list = ( PtrToNode )malloc( sizeof( struct Node ) ); list->Data = num; list->Next = NULL; last = list; len--; while( len-- ){ scanf( "%d",&num ); node= ( List )malloc(sizeof(struct Node)); node->Data = num; node->Next = NULL; last->Next = node; last = node; } return list;} void Print( List L ) { if(L==NULL) return ; else while(L!=NULL){ printf("%d ",L->Data); L=L->Next; } putchar('/n'); } List Reverse( List L ){ PtrToNode t=NULL; PtrToNode newlist=NULL; while(L!=NULL){ t=L->Next; //用t保存L的下一個節(jié)點,否則L->next就丟失了,方便L的移動 L->Next=newlist;//L指向它的前一個節(jié)點 newlist=L; //newlist指向已經(jīng)逆轉(zhuǎn)的最后一個節(jié)點 L=t; //將L移動到下一個元素 } return newlist;} 
新聞熱點
疑難解答