该程序实现了链表的增、删、遍历、排序等大部分功能,仅供参考。理解链表的原理,对后面栈、队列、二叉树、图等数据结构的学习有很大帮助。
链表的实现:
# include <stdio.h> # include <malloc.h> # include <stdlib.h> typedef struct Node { int data; struct Node * pNext; }NODE, *PNODE; PNODE create_list(void); void traverse_list(const PNODE); bool is_empty(PNODE); int length_list(PNODE); bool sort_list(PNODE); bool insert_list(PNODE); bool delete_list(PNODE); int main(void) { PNODE pHead = (PNODE)malloc(sizeof(NODE)); pHead = create_list(); traverse_list(pHead); is_empty(pHead); int len = length_list(pHead); printf("链表的长度为:%d\n", len); printf("排序后:\n"); sort_list(pHead); traverse_list(pHead); insert_list(pHead); traverse_list(pHead); delete_list(pHead); traverse_list(pHead); return 0; } PNODE create_list(void) { int i; int val; int len; PNODE pHead = (PNODE)malloc(sizeof(NODE)); PNODE pTail = pHead; pTail->pNext = NULL; printf("请输入节点的个数:len = "); scanf("%d", &len); for (i=0; i<len; ++i) { printf("请输入第%d个节点数据: val = ", i+1); scanf("%d", &val); PNODE pNew = (PNODE)malloc(sizeof(NODE)); if (NULL == pNew) { printf("内存空间分配失败!\n"); exit(-1); } pNew->data = val; pTail->pNext = pNew; pNew->pNext = NULL; pTail = pNew; } return pHead; } void traverse_list(const PNODE pHead) { PNODE p = pHead->pNext; if(NULL == p) { printf("链表为空!\n"); return; } printf("\n链表中的数据为:\n"); while (NULL != p) { printf("%d ", p->data); p = p->pNext; } printf("\n"); return; } bool is_empty(PNODE pHead) { PNODE p = pHead; if(NULL == p->pNext) { return true; } else { return false; } } int length_list(PNODE pHead) { int len = 0; PNODE p = pHead; while (NULL != p->pNext) { ++len; p = p->pNext; } return len; } bool sort_list(PNODE pHead) { int i, j; int t; int len; PNODE p, q; if ( is_empty(pHead) ) { printf("链表为空!\n"); return false; } else { len = length_list(pHead); for (i=0, p=pHead->pNext; i<len-1; ++i, p=p->pNext) { for (j=i+1, q=p->pNext; j<len; ++j, q=q->pNext) { if (p->data > q->data) { t = p->data; p->data = q->data; q->data = t; } } } return true; } } bool insert_list(PNODE pHead) { int i = 0; int pos, val; PNODE p = pHead; printf("请输入您要插入的位置:pos = "); scanf("%d", &pos); //判断输入位置pos的正确性并使指针后移,使指针p指向最后一个结点。此语句非常经典! while (NULL!=p && i<pos-1) { p = p->pNext; ++i; } if (i>pos-1 || NULL==p) //判断位置的正确性及指针p的是否为空,防止程序崩溃。 { printf("输入错误,插入失败!\n"); return false; } printf("请输入您要插入的数据:val = "); scanf("%d", &val); PNODE pNew = (PNODE)malloc(sizeof(NODE)); if (NULL == pNew) { printf("内存分配失败!\n"); exit(-1); } pNew->data = val; pNew->pNext = p->pNext; p->pNext = pNew; return true; } bool delete_list(PNODE pHead) { int i = 0; int pos, val; PNODE p = pHead; printf("请输入您要删除的位置:pos = "); scanf("%d", &pos); while (NULL!=p->pNext && i<pos-1) { p = p->pNext; ++i; } if (NULL==p->pNext || i>pos-1) { printf("输入错误,删除失败!\n"); return false; } PNODE q = p->pNext; val = q->data; //删除p后面的结点 p->pNext = p->pNext->pNext; free(q); q = NULL; printf("删除成功,您删除的数据为:%d", val); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/lfhappypain/article/details/47292771