链表插入操作案例测试给大家参考下
看见大家总是在问链表的问题,虽然简单,但里面坑还是很多的,总结了下给大家参考。程序代码:
#include <stdio.h> #include <malloc.h> struct Test { int nVal; struct Test* pNext; }; struct Test* pHead = NULL; //头部插入 void HeadInsert(int val) { struct Test* pNew = NULL; pNew = (struct Test*)malloc(sizeof(struct Test)); pNew->nVal = val; //将新节点的pNext指向头指针 pNew->pNext = pHead; //将头指针重新指向新节点完成头部插入 pHead = pNew; } //尾部插入 void TailInsert(int val) { struct Test* pNew = NULL; struct Test* pTmp1 = pHead; struct Test* pTmp2 = pHead; pNew = (struct Test*)malloc(sizeof(struct Test)); pNew->nVal = val; //跳出循环当前指针为空 while(pTmp1 != NULL) { //记录pTmp1的前一个指针 pTmp2 = pTmp1; //当前指针 pTmp1 = pTmp1->pNext; } //注意不赋值为空遍历会访问未知空间错误 pNew->pNext = NULL; //注意这里需要判断是否头指针为空 if(pHead == NULL) { pHead = pNew; } else { //将当前指针的前一个指针的pNext指向新指针 pTmp2->pNext = pNew; } } //任意位置插入 void Insert(int val, int pos) { struct Test* pNew = NULL; struct Test* pTmp1 = pHead; struct Test* pTmp2 = pHead; int i = 1; pNew = (struct Test*)malloc(sizeof(struct Test)); pNew->nVal = val; pNew->pNext = NULL; while(pTmp1 != NULL && i <= pos) { if(i == pos) { //将新节点的pNext指向当前结点 pNew->pNext = pTmp1; //很重要 if(i == 1) { //第一个位置直接头节点指向新节点 pHead = pNew; } else { //将当前指针的pNext前一个指针指向新节点 pTmp2->pNext = pNew; } return; } //记录pTmp1的前一个指针 pTmp2 = pTmp1; //当前指针 pTmp1 = pTmp1->pNext; i++; } //未找到插入位置处理 if(i > pos || pTmp1 == NULL) { printf("位置未找到头部插入\n"); pNew->pNext = pHead; pHead = pNew; } } void Traver() { struct Test* pTmp = pHead; while(pTmp != NULL) { printf("%d ", pTmp->nVal); pTmp = pTmp->pNext; } printf("\n\n"); } int main() { int i = 0; printf("在0位置插入1000:\n"); Insert(1000, 0); Traver(); printf("尾部插入6-9:\n"); for(i = 6; i < 10; i++) { TailInsert(i); } Traver(); printf("头部插入0-5:\n"); for(i = 0; i < 6; i++) { HeadInsert(i); } Traver(); printf("尾部插入10-15:\n"); for(i = 10; i < 16; i++) { TailInsert(i); } Traver(); printf("在第1个位置插入111:\n"); Insert(111, 1); Traver(); printf("在第2个位置插入222:\n"); Insert(222, 2); Traver(); printf("在第100个位置插入100:\n"); Insert(100, 100); Traver(); printf("在第20个位置插入2000:\n"); Insert(2000, 20); Traver(); return 0; }
[此贴子已经被作者于2017-3-17 23:42编辑过]