No pain, no gain.|

GJ504b

园龄:6个月粉丝:2关注:2

单链表

单链表

alt text

alt text

alt text

/*单链表*/
#include<stdio.h>
#include<stdlib.h>

typedef struct Node {
	int data;
	struct Node* next;
}Node;

Node* initList(){
	Node* list = (Node*)malloc(sizeof(Node));
	list -> data = 0;
	list -> next = NULL;
	return list;
}

void headList(Node* list, int data){
	Node* node = (Node*)malloc(sizeof(Node));
	node -> data = data;
	node -> next = list -> next;
	list -> next = node;
	list -> data ++;
}

void tailList(Node* list, int data){
	Node* head = list;
	Node* node = (Node*)malloc(sizeof(Node));
	node -> data = data;
	node -> next = NULL;
	list = list -> next;
	while(list -> next){
		list = list -> next;
	}
	list -> next = node;
	head -> data ++;
}

void deleList(Node* list, int data){
	Node* pre = list;
	Node* current = list -> next;
	while(current){
		if(current -> data == data){
			pre -> next = current ->next;
			free(current);
			break;//不加break为什么就死循环了
		}
		pre = current;
		current = current -> next;
	}
	list -> data --;
}
/*为什么不加break就不打印???
free 函数不会改变 current 变量本身
它只是释放了 current 指向的内存
如果 current 在 free 之后没有被重新赋值
它仍然会指向已经被释放的内存区域
这会导致未定义行为,包括潜在的死循环。
*/
void deleListAll(Node* list, int data){
    Node* pre = list;
    Node* current = list->next;
    while(current){
        if(current->data == data){
            pre->next = current->next; // 删除当前节点
            free(current);             // 释放当前节点的内存
            current = pre->next;       // 更新 current 指向下一个节点
            list->data--;              // 更新链表长度
        } else {
            pre = current;             // 更新 pre 为当前节点
            current = current->next;   // 更新 current 为下一个节点
        }
    }
}

void printList(Node* list){
	list = list -> next;
	while(list){
		printf("%d ",list -> data);
		list = list -> next;
	}
	printf("\n");
}
int main(){
	Node* list = initList();
	headList(list, 1);	
	headList(list, 2);
	headList(list, 1);
	headList(list, 4);
	headList(list, 5);
	tailList(list, 6);
	tailList(list, 7);
	tailList(list, 8);
	tailList(list, 9);
	tailList(list, 10);
	deleList(list, 9);
	deleListAll(list, 1);
	printList(list);
	return 0;
}//5 4 2 6 7 8 10

本文作者:GJ504b

本文链接:https://www.cnblogs.com/GJ504b/p/18679044

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   GJ504b  阅读(5)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起