赞
踩
链表
单项链表一般有三种插入方式
1.头插,在头节点后,首节点前插入
2.尾插,从末尾插入
3.从任意位置插入
- int input_func(Link *pHead,int pos,data_type item)
- {
- int i;
- if(NULL == pHead)
- {
- perror("pHead_NULL");
- return -1;
- }
- Link *pNew = NULL;
- pNew = (Link *)malloc(sizeof(Link));
- if(NULL == pNew)
- {
- perror("pNew_MALLOC_ERROR!");
- return -1;
- }
- Link *pPre = NULL;
- //定义一个位置插入
- Link *pTail = NULL;
- switch(pos)
- {
- //首插法
- case 1:
- if(pHead->pNext != NULL)
- {
- pNew->pNext = pHead->pNext;
- }
- pHead->pNext = pNew;
- pNew->data = item;
- break;
- //尾插法
- case -1:
- pTail = pHead;
- while(pHead->pNext != NULL)
- {
- pTail = pTail->pNext;
- }
- pTail->pNext = pNew;
- pNew->data = item;
- break;
- //从任意位置插入
- case 2:
- pPre = pHead;
- //找到要插入节点的前一个节点
- //当pPre不为空的情况下移动pos-1次
- while(pPre != NULL & i<pos-1)
- {
- pPre = pPre->pNext;
- i++;
- }
- //保护插入节点后的所有节点
- pNew->pNext = pNew;
- //插入
- pPre->pNext=pNew;
- break;
- }
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。