C语言中 链表的 增加一个节点和删除一个节点
#include<stdio.h>
typedef struct node {
int val;
struct node * p_next;
} node_t;
int main()
{
node_t node1 ={10},node2 ={20},node3={30} ,head = {0}, tail = {0};
head.p_next = &node1;
node1.p_next = &node2;
node2.p_next = &node3;
node3.p_next = &tail;
node_t * p_tmp = NULL, *p_first = NULL, *p_mid = NULL,*p_last = NULL;
node_t node4 = {25};
// add one node
for(p_tmp = &head; p_tmp != &tail; p_tmp = p_tmp->p_next)
{
p_first = p_tmp;
p_mid = p_first->p_next;
p_last = p_mid->p_next;
if (p_mid->val >= node4.val || p_mid == &tail) // 如果比其他的都大,则插入到最后
{
p_first->p_next = &node4;
node4.p_next = p_mid;
//printf("insert p_mid = %d\n",p_mid->val);
break; // 插入以后,需要直接break
}
}
//delete one node
for(p_tmp = &head ;p_tmp != &tail;p_tmp = p_tmp->p_next)
{
p_first = p_tmp;
p_mid = p_first->p_next;
p_last = p_mid->p_next;
if(p_mid->val == 20 && p_mid != &tail) // 如果删除的值恰好等于节点中的值 并且 不是尾节点
{
p_first->p_next = p_last;
break;
}
}
for (p_tmp = &head;p_tmp != &tail ;p_tmp = p_tmp->p_next)
{
p_first = p_tmp;
p_mid = p_tmp->p_next;
p_last = p_mid->p_next;
if(p_mid != &tail)
{
printf("%d\n",p_mid->val);
}
}
return 0;
}