#include <stdio.h> #include <stdlib.h> typedef struct Node { int data; //数据域 Node *next; //指针域,指向下一个Node节点 }Node; Node *create(); //创建一个单链表 int deleteFromList(Node *linkList, int i); //删除节点 成功返回0 否则-1 int insertIntoList(Node *linkList, int i, int value);//插入节点 成功返回0 否则-1 void display(Node *linkList);//遍历并打印链表 void main() { Node *LinkList = create(); // display(LinkList); insertIntoList(LinkList, 5, 30); display(LinkList); deleteFromList(LinkList, 5); display(LinkList); } Node *create() { int n = 20; Node *pList, *pNew, *pTail; pList = (Node *)malloc(sizeof(Node)); pList->next = NULL; pTail = pList;// for(int i = 1; i <= n; i++) { pNew = (Node *)malloc(sizeof(Node)); if(pNew == NULL) { printf("error!!"); exit(0); } pNew->data = i; pNew->next = NULL; pTail->next = pNew; pTail = pNew; } pTail->next = NULL; return pList; } int insertIntoList(Node *linkList, int i, int value) { //先查找是否有这个节点 Node *p, *q; int j = 1; //计数 p = linkList; while(p && j < i) //寻找第i个节点 { p = p->next; ++j; } if(!p || j > i) { return -1;//第i个节点不存在,插入失败 } //现在p是在第4个位置,p->next指向的是第五个值 q = (Node *)malloc(sizeof(Node)); q->data = value; q->next = p->next;//把第五个值及以后的链表下挂到q->next指针上 p->next = q; //把q及上面下挂在q->next上的链接 下挂到p->next上 return 0; } int deleteFromList(Node *linkList, int i) { //检测是否存在第i个节点 Node *Ptr; int j = 1; Ptr = linkList; while(Ptr->next && j < i) { Ptr = Ptr->next; ++j; } if(!(Ptr->next) || j > i) { return -1;//不存在第i个节点 } Ptr->next = Ptr->next->next; return 0; } void display(Node *linkList) { while(linkList->next) { printf("%d\n", linkList->next->data); linkList = linkList->next; } }