#include <stdio.h>
#include <stdlib.h>
typedef struct _NODE{
int data;
struct _Node *next;
}Node;
/*
建立带有头结点的单向链表,循环创建结点,结点数据域中的数值从键盘输入,
以 -1 作为输入结束标志,链表的头结点地址由函数值返回.
*/
Node* init_linkedlist(){
Node* head = NULL;
head = (Node*)malloc(sizeof(Node));
if(head == NULL){
return NULL;
}
head->data = -1;
head->next = NULL;
Node* curNode = head;
int data=-1;
while(1){
printf("please input data:\n");
scanf("%d", &data);
if(data == -1){
break;
}
Node* temp = (Node*) malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
curNode->next = temp;
curNode = curNode->next;
}
return head;
}
/*
遍历列表
*/
void foreach(Node* head){
if(head == NULL){
return;
}
Node* temp = head->next;
while(temp != NULL){
printf("%d\n", temp->data);
temp = temp->next;
}
}
/*
插入节点
在指定值后面插入数据data,如果值val不存在,则在尾部插入
*/
void insert(Node* head, int val, int data){
if(head == NULL){
return;
}
Node* pre = head;
Node* temp = pre->next;
while(temp != NULL){
if(temp->data == val){
break;
}
pre = temp;
temp = temp->next;
}
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
if(temp == NULL){
printf("不存在值为%d的节点!\n", val);
pre->next = newNode;
return;
}
newNode->next = temp->next;
temp->next = newNode;
}
/*
删除节点
*/
void delete(Node* head, int val){
if(head == NULL){
return;
}
Node* pre = head;
Node* cur = pre->next;
while(cur != NULL){
if(cur->data == val){
break;
}
pre = cur;
cur = cur->next;
}
if(cur != NULL){
Node* temp = cur;
pre->next = cur->next;
free(temp);
temp->next = NULL;
}
}
/*
销毁列表
*/
void destroy(Node* head){
if(head == NULL){
return;
}
Node* pre = head;
Node* cur = pre->next;
while(cur != NULL){
Node* temp = cur;
cur = cur->next;
pre->next = cur;
free(temp);
temp->next = NULL;
}
}
void test(){
Node* head = init_linkedlist();
insert(head, 5, 6);
foreach(head);
delete(head, 5);
foreach(head);
destroy(head);
}
int main(){
test();
}
C语言实现单链表
最新推荐文章于 2025-05-19 19:37:25 发布