关于单链表的第二稿,对其中的函数实现进行了些优化,改善了打印函数的鲁棒性——可以打印空链表了 /************************************************************************/ /* author : thomas E-mail: chenhua308@gmail.com 2011-5-13 in lab of NJUPT */ /************************************************************************/ #include <stdio.h> #include <malloc.h> typedef struct tag { int data; struct tag *next; } node, *nodep; node *creat( int num ) { nodep p; p = ( nodep )malloc( sizeof( node ) ); p -> data = num; p -> next = NULL; return p; } int length( node *head ) { int n = 0; node *p; p = head; while ( p != NULL ) { n++; p = p ->next; } return n; } void print( node *head ) { node *p; int i = 0; int n = length(head); p = head; if ( p == NULL ) { printf("the list is empty! /n"); } else { printf("these %d records are : /n", n); for ( i = 1; i <=n; i++) { printf("the %d record is: %d /n", i, p -> data ); if ( i != n) { p = p -> next; } } } } void insertascend( nodep *head, int num ) { nodep previous, current, p; current = *head; previous = NULL; while ( current != NULL && current -> data < num ) { previous = current; current = current -> next; } p = (nodep)malloc(sizeof(node)); p -> data = num; p -> next = current; if ( previous == NULL ) *head = p; else previous -> next = p; } void insertdown( nodep *head, int num ) { nodep previous, current, p; current = *head; previous = NULL; while ( current != NULL && current -> data > num ) { previous = current; current = current -> next; } p = ( nodep )malloc( sizeof( node ) ); p -> data = num; p -> next = current; if ( previous == NULL ) *head = p; else previous -> next = p; } void del( nodep *head, int num ) { nodep current = *head; nodep previous = NULL; while ( current != NULL && current -> data != num ) { previous = current; current = current -> next; } if ( current == NULL ) { printf("%d not found! /n", num); } else { if ( previous == NULL ) *head = current -> next; else previous -> next = current -> next; free(current); } } nodep reverse( nodep head ) { node *p1, *p2, *p3; if ( head == NULL || head -> next == NULL ) { return head; } p1 = head; p2 = head -> next; while ( p2 ) { p3 = p2 -> next; p2 -> next = p1; p1 = p2; p2 = p3; } head -> next = NULL; head = p1; return head; } void main(int argc, char *argv[]) { nodep head; head = creat(4); print(head); //insertdown( &head, 3); insertascend( &head, 3); print(head); //insertdown( &head, 5); insertascend( &head, 5); print(head); del( &head, 4 ); print(head); }