#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *Next;
/* data */
};
typedef struct Node node;
node *Link;
// 创建一个新的节点
node *CreateNewNode(int data)
{
node *NewNode = (node *)malloc(sizeof(node));
if (NewNode == NULL)
exit(1);
NewNode->data = data;
NewNode->Next = NULL;
return NewNode;
}
// 在链表末尾插入一个节点
node *InsertNode(node *head, int data)
{
node *new_node = CreateNewNode(data);
node *temp_node;
temp_node = head;
if (temp_node == NULL)
{
return new_node;
}
while (temp_node->Next != NULL)
{
temp_node = temp_node->Next;
}
temp_node->Next = new_node;
return head;
}
// 头插法
node *insertNodeBegin(node *head, int data)
{
node *newNode = CreateNewNode(data);
if (head == NULL)
return newNode;
newNode->Next = head->Next;
head->Next = newNode;
return head;
}
// 打印链表
void print_chain(node *head)
{
node *temp;
temp = head;
while (temp->Next != NULL)
{
printf("%d-->", temp->data);
temp = temp->Next; // 更新链表
}
printf("NULL\r\n");
}
// 删除某一个节点
node *DeleNode(node *head, int data)
{
node *temp_node = head;
node *dele_node = NULL;
if (temp_node->data == data)
{
head = temp_node->Next;
free(temp_node);
return head;
}
while (temp_node->Next != NULL)
{
if (temp_node->Next->data == data)
{
dele_node = temp_node->Next;
temp_node->Next = dele_node->Next;
break;
}
temp_node = temp_node->Next;
}
if (dele_node != NULL)
{
free(dele_node);
}
return head;
}
int main()
{
node *head = NULL;
head = InsertNode(head, 10);
head = InsertNode(head, 20);
head = InsertNode(head, 30);
head = InsertNode(head, 40);
head = insertNodeBegin(head, 50);
print_chain(head);
head = DeleNode(head, 30);
print_chain(head);
}
标签:node,head,单链,temp,Next,插入,NULL,data,节点 From: https://blog.csdn.net/qiuhao1314520/article/details/144914767