本次主要介绍从尾部添加新节点
1、定义节点结构
数据域:int x
指针域:struct Node *next
typedef struct Node
{
int x;
struct Node *next;
}node;
2、动态添加新节点
头结点:head
尾节点:tail
插入节点:ins
通过将 tail->next = ins(将插入节点 插入链表尾部) ,设置 tail = ins (设置插入节点为尾节点),并且将 tail->next = NULL
node *head = NULL;
head = (node *)malloc(sizeof(node));
head->x = 99;
node *tail = head;
for (int i = 0; i < 10; i++)
{
node *ins = (node *)malloc(sizeof(node));
ins->x = i;
tail->next = ins;
tail = ins;
tail->next = NULL;
}
3、顺序遍历节点
node *p=head;
while (p!= NULL)
{
printf("%d\n", p->x);
p = p->next;
}
4、在pos位置插入新节点
void insertNode(int pos,int val,node *h)
{
node *temp = (node *)malloc(sizeof(node));
temp->x = val;
int count = 0;
while (h != NULL)
{
if (count == pos-1)
{
temp->next = h->next;
h->next = temp;
}
count++;
h = h->next;
}
temp = NULL;
}
5、在删除pos位置节点
//删除节点
void deleteNode(int pos, node *h)
{
int count = 0;
while (h != NULL)
{
if (count == pos-1)
{
if (h->next != NULL)
{
node* temp = h->next; //定义临时temp指向要删除的节点
h->next = temp->next; //将要被删除的节点的前驱节点指向其后继节点
free(temp); //释放被删除节点的内存空间,防止内存泄漏
temp = NULL; //将temp指向NULL,防止产生野指针
return;
}
else
{
printf("该节点不存在\n");
return;
}
}
count++;
h = h->next;
}
printf("该节点不存在\n");
}
6、查询pos位置节点
node* findVal(int data,node *h)
{
node *val = (node *)malloc(sizeof(node));
val = h;
int count = 1;
while (val != NULL)
{
if (val->x == data)
printf("找到数据为%d的节点,该节点是第%d个\n", data, count);
count++;
val = val->next;
}
return val;
}