关于单链表的题目
编写程序实现以下功能:(1)产生10个0~99之间的随机整数,依次保存到单链表;输出单链表各结点值。
(2)从该单链表删除与给定值相等的所有结点。输出变化后的单链表各结点值,并输出单链表的长度。
(3)将该单链表的各结点值逆序保存到数组中,输出数组各元素值。
[ 本帖最后由 landielingwu 于 2010-3-20 11:14 编辑 ]
#include <stdio.h> #include <stdlib.h> #include <time.h> typedef struct{ int num; }DATA; typedef struct node NODE; struct node{ DATA item; NODE* link; }; NODE* buildList(void); bool searchNode(NODE* randnum, NODE** pPre, NODE** pCur, int a); NODE* insertNode(NODE* randnum, NODE* pPre, DATA item); void printList(NODE* randnum); NODE* deleteNode(NODE* randnum, NODE* pPre, NODE* pCur); NODE* deleteData(NODE* randnum); int* arydesc(NODE* randnum, int* count); int main (void) { NODE* randnum; randnum = NULL; int* ary; int count; printf("Before delete: \n"); randnum = buildList(); printList(randnum); printf("\nAfter delete duplicate:\n"); randnum = deleteData(randnum); printList(randnum); printf("\nAfter put in array descending:\n"); ary = arydesc(randnum, &count); for(int i = 0; i < count; i++) printf("%d\n", ary[i]); return 0; } NODE* buildList(void) { DATA item; NODE* pPre; NODE* pCur; NODE* randnum; randnum = NULL; srand(time(NULL)); for(int i = 0; i < 10; i++) { item.num = rand()% 10 + 0; searchNode(randnum, &pPre, &pCur, item.num); randnum = insertNode(randnum, pPre, item); } return randnum; } bool searchNode(NODE* randnum, NODE** pPre, NODE** pCur, int a) { bool found = false; *pPre = NULL; *pCur = randnum; while(*pCur && a > (*pCur)->item.num) { *pPre = *pCur; *pCur = (*pCur)->link; } if(*pCur && a == (*pCur)->item.num) found = true; return found; } NODE* insertNode(NODE* randnum, NODE* pPre, DATA item) { NODE* pNew; if(!(pNew = (NODE*) malloc (sizeof(NODE)))) printf("Memory overflow when malloc!\n"); pNew->item = item; if(!pPre) { pNew->link = randnum; randnum = pNew; } else { pNew->link = pPre->link; pPre->link = pNew; } return randnum; } void printList(NODE* randnum) { NODE* pWalker; int count = 0; pWalker = randnum; while(pWalker) { printf("%d\n", pWalker->item.num); pWalker = pWalker->link; count++; } printf("Total length: %d\n", count); } NODE* deleteNode(NODE* randnum, NODE* pPre, NODE* pCur) { if(!pPre) randnum = pCur->link; else pPre->link = pCur->link; free(pCur); return randnum; } NODE* deleteData(NODE* randnum) { NODE* pCur; NODE* pPre; NODE* pHead; NODE* pWalker; int a = -1; pWalker = randnum; while(pWalker) { if(a == pWalker->item.num) { searchNode(randnum, &pPre, &pCur, pWalker->item.num); //这里偶尔会出错为什么? deleteNode(randnum, pPre, pCur); } else a = pWalker->item.num; pWalker = pWalker->link; } return randnum; } int* arydesc(NODE* randnum, int* a) { NODE* pWalker; int count = 0; int i = 0; int* ary; pWalker = randnum; while(pWalker) { pWalker = pWalker->link; count++; } *a = count; ary = (int*) malloc (count * sizeof(int)); pWalker = randnum; while(i < count) { ary[count - i - 1] = pWalker->item.num; pWalker = pWalker->link; i++; } return ary; }