链表的插入
程序代码:
# include <stdio.h> # include <stdlib.h> typedef struct node { int date; struct node *pNext; }NODE, *PNODE; PNODE init_list(int *len)//初始化链表 { PNODE pHead, pRecord, pTemp; int i; pHead = NULL; printf("请输入链表的长度: "); scanf("%d", len); for (i=0; i<*len; i++) { pTemp = (PNODE) malloc(sizeof(NODE)); if (NULL == pTemp) { printf("分配失败,程序终止!\n"); exit(-1); } pTemp->pNext = NULL; printf("节点的值 : "); scanf("%d", &pTemp->date); if (NULL == pHead) { pHead = pTemp; pRecord = pHead; } else { pRecord->pNext = pTemp; pRecord = pTemp; } } return pHead; } void traverse_list(PNODE pHead)//遍历链表 { PNODE pTemp = pHead; while (NULL != pTemp) { printf("%d ", pTemp->date); pTemp = pTemp->pNext; } printf("\n"); } bool insert_list(PNODE pHead, int pos, int len, int e)//插入元素 { if (pos<1 || pos>len+1) { printf("pos 输入错误!\n"); return false; } PNODE pTemp; PNODE pRecord = pHead; pTemp = (PNODE) malloc(sizeof(NODE)); if (NULL == pTemp) { printf("分配失败,程序终止!\n"); exit(-1); } pTemp->pNext = NULL; pTemp->date = e; if (1 == pos) { pHead = pTemp; pTemp->pNext = pRecord; } else { for (int i=1; i<=pos; i++) { if (pos-1 == i) { pTemp->pNext = pRecord->pNext; pRecord->pNext = pTemp; break; } pRecord = pRecord->pNext; } } return true; } int main() { PNODE pHead = NULL; int length = 0; int e, pos; pHead = init_list(&length); printf("未处理的链表 : \n"); traverse_list(pHead); printf("输入插入的位置及元素 : "); scanf("%d %d", &pos, &e); insert_list(pHead, pos, length, e); printf("插入后的链表 : \n"); traverse_list(pHead); return 0; }
怎么每次输入pos == 1的时候插入不成功;
输入其它的值都可以,源代码怎么修改呀
[此贴子已经被作者于2016-3-14 22:23编辑过]