C和指標 十二章 雙鏈表沒有實現
阿新 • • 發佈:2019-02-05
這一章主要講了連結串列;
單鏈表和雙鏈表,由於某些原因,只實現了單鏈表;雙鏈表等我看到後邊資料結構再回來補上去
#include <stdio.h> #include <stdlib.h> //這段程式碼參考了c和指標以及深入淺出C語言程式設計連結串列一部分,但是插入元素的那段程式碼是深入淺出那裡的,比較簡單 typedef struct NODE { int value; struct NODE *link; } Node; Node *head; //使用陣列建立動態連結串列,先建立頭節點,再建立第一個資料節點,並連線到頭節點後面,如果再有新資料就再建立節點 Node *creatlist( int *a, int n); void outputlist( Node *head);//連結串列輸出 void insertlist( Node *head, int x );//插入一個值 void deletelist( Node *head, int new_value ); int main() { int a[10]= { 10, 20, 30, 40, 50 }, i; printf("陣列初值是 \n"); for( i = 0; i < 5; i++ ) { printf( "%d\t", a[i]); } printf("\n"); head = creatlist( a, 5 ); printf( "使用陣列元素建立的動態連結串列:\n"); outputlist( head ); int x; x=25; insertlist( head, x ); deletelist( head, x ); outputlist( head ); return 0; } Node *creatlist( int *a, int n) { Node *head, *p1, *p2; int i; head = (Node *) malloc( sizeof( Node ) ); if( head == NULL) { printf("沒有分配足夠記憶體"); exit(0); } p1 = head; for( i = 0; i < n; i++ ) { p2 = malloc( sizeof( Node ) ); if( p2 == NULL) { printf("沒有分配足夠記憶體"); exit(0); } p1->link = p2; p2->value = a[i]; p1 = p2; } p1->link = NULL; return head; } void outputlist( Node *head)//輸出連結串列 { Node *p; p = head->link; printf("head->"); while( p != NULL ) { printf("%d->", p->value); p = p->link; } printf("NULL\n"); } void insertlist( Node *head, int new_value ) { Node *current; Node *precious; Node *news; precious = head; current = head->link; while( current != NULL ) { if( current->value < new_value ) { precious = current; current = current->link; } else break; } news =(Node *) malloc( sizeof (Node) ); if (news == NULL) { printf("出錯\n"); exit(0); } news->value = new_value; news ->link = current; precious->link = news; outputlist( precious ); } void deletelist( Node *head, int new_value ) { Node *current; Node *precious; precious = head; int flag; current = head->link; while( current != NULL ) { if( current->value == new_value ) { flag = 1; break; } precious = current; current = current->link; } if( flag == 1) { precious->link = current->link; } outputlist( precious ); }