单链表

来源:互联网 发布:ubuntu嵌入式工控机 编辑:程序博客网 时间:2024/06/05 20:57
/* * main.cpp * *  Created on: 2016-10-13 *      Author: llf05 */# include <stdio.h># include <stdlib.h># include <stdbool.h>typedef struct Node{int data;struct Node*pNext;} Node, *pNode;pNode creat_list(int len);  //len为链表结点的长度;void traverse_list(pNode pHead);bool is_empty(pNode pHead);int len_list(pNode pHead);void sort_list(pNode pHead);void insert_list(pNode, int, int);void delete_list(pNode pHead, int pos, int *val);int main(void){pNode pHead = NULL;pHead = creat_list(5); //创建一个非循环单链表,将该链表的头结点赋值给pHeadtraverse_list(pHead);if (is_empty(pHead)){printf("link is empty\n");}elseprintf("link is not empty\n");printf("list len = %d\n", len_list(pHead));sort_list(pHead);printf("...............insert..............\n");insert_list(pHead, 3, 22);traverse_list(pHead);int num;printf("...............delete..............\n");delete_list(pHead, 7, &num);printf("delete num is %d\n", num);traverse_list(pHead);return 0;}pNode creat_list(int len)  //len为链表结点的长度{int i, val;pNode pHead = (pNode)malloc(sizeof(Node));pNode pTail = pHead;pTail->pNext = NULL;if (NULL == pHead){printf("malloc fail\n");exit(-1);}for (i=0; i<len; ++i){scanf("%d", &val);pNode pNew = (pNode)malloc(sizeof(Node));pNew->data = val;pTail->pNext = pNew;pNew->pNext = NULL;pTail = pNew;}printf("crate finish\n");return pHead;}void traverse_list(pNode pHead){pNode p = pHead->pNext; //让p指向第一个有效结点while(NULL != p){printf("%d ", p->data);p = p->pNext;}printf("\ntraverse finish\n");}bool is_empty(pNode pHead){if (NULL == pHead->pNext){return true;}return false;}int len_list(pNode pHead){pNode p;int len = 0;p = pHead;while(p->pNext != NULL){len++;p = p->pNext;}return len;}void sort_list(pNode pHead){pNode p, q;int len = len_list(pHead);int i, j, t;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;}}void insert_list(pNode pHead, int pos, int val){int i = 0;pNode p = pHead;while(NULL!=p && i<pos-1){p = p->pNext;++i;}if (i>pos-1 || NULL==p){return;}pNode pNew = (pNode)malloc(sizeof(Node));if (NULL == pNew){exit(-1);}pNew->data = val;pNode q = p->pNext;p->pNext = pNew;pNew->pNext = q;}void delete_list(pNode pHead, int pos, int *pVal){int i = 0;pNode p = pHead;while(NULL!=p && i<pos-1){p = p->pNext;++i;}if (i>pos-1 || NULL==p->pNext){printf("delete error\n");return;}pNode q = p->pNext;*pVal = q->data;p->pNext = p->pNext->pNext;free(q);q = NULL;}

0 0
原创粉丝点击