C语言链表的一般操作,创建,插入,遍历,删除
2016-06-22 14:32
501 查看
#include "stdlib.h" #include "stdio.h" #include "string.h" typedef struct Node { int data; struct Node *next; }SLIST; // 尾插法创建链表 SLIST *Creat_SList() { //1 创建头结点并初始化 SLIST *pHead = NULL; SLIST *pCur = NULL; SLIST *pM = NULL; int data = 0; pCur = pHead = (SLIST *)malloc(sizeof(SLIST)); pHead->data = 0; pHead->next = NULL; //2循环创建结点,结点数据域中的数值从键盘输入, //以-1作为输入结束标志 printf("\nPlease enter the data of node(-1:quit) "); scanf("%d", &data); while(data != -1) { pM = (SLIST*)malloc(sizeof(SLIST)); pM->data = data; pM->next = NULL; pCur->next = pM; pCur = pM; printf("\nPlease enter the data of node(-1:quit) "); scanf("%d", &data); } return pHead; } int SList_Print(SLIST *pHead) { SLIST* pCur = NULL; if (!pHead) { return -1; } pCur = pHead->next; while (pCur) { printf("%d\n", pCur->data); pCur = pCur->next; } return 1; } //在结点数值为x的前面插入y int SList_NodeInsert(SLIST *pHead, int x, int y) { SLIST* pM = NULL; SLIST* pCur = NULL; SLIST* pLast = NULL; if (!pHead) { return -1; } pLast = pHead; pCur = pHead->next; pM = (SLIST*)malloc(sizeof(SLIST)); pM->data = y; pM->next = NULL; while (pCur) { if (pCur->data == x) { break; } pLast = pCur; pCur = pCur->next; } pM->next = pCur; pLast->next = pM; return 1; } //删除结点为y的链表结点 int SList_NodeDel(SLIST *pHead, int y) { SLIST* pCur = NULL; SLIST* pLast = NULL; if (!pHead) { return -1; } pLast = pHead; pCur = pHead->next; while (pCur) { if (pCur->data == y) { break; } pLast = pCur; pCur = pCur->next; } if (!pCur) { return -1; } pLast->next = pCur->next; free(pCur); return 1; } int SList_Destory(SLIST *pHead) { SLIST* pNext = NULL; SLIST* pCur = NULL; if (!pHead) { return -1; } pCur = pHead; pNext = pCur->next; while (1) { free(pCur); pCur = pNext; if (!pCur) { break; } pNext = pNext->next; } return 1; } int main() { SLIST* pHead = Creat_SList(); if (!pHead) { return -1; } SList_Print(pHead); SList_NodeInsert(pHead, 20, 19); SList_Print(pHead); SList_NodeDel(pHead, 19); SList_Print(pHead); SList_Destory(pHead); return 0; }
相关文章推荐
- C语言关键字用法
- 深入理解C++中的mutable关键字
- C语言动态分配数组
- C/C++基础——set的基本操作总结
- CBF中for循环变矩阵乘法的思想(arrayfire)--复数矩阵
- C++中文件流(fstream)的使用方法及示例
- *leetcode #136 in cpp
- 浅析C++多态性
- Google C++ 编码规范(中文版)
- *leetcode #135 in cpp
- 国内C/C++刷题网站汇总
- C语言正则表达式详解 regcomp() regexec() regfree()详解
- *leetcode #134 in cpp
- c++对象内存布局(虚表和虚指针)
- C++ continue 和 break 的用法
- Win32下C++遍历目录和文件的源码
- C++ 输入字符串和string 类型总结
- C/C++中调用api设置mysql连接的编码方式
- static全解
- C++之类的成员函数的原理