题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f?tpId=308&tqId=2372688&ru=/exam/oj&qru=/ta/algorithm-start/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D308
#include<stdio.h> #include<stdlib.h> #include<string.h> #define true 1 #define false 0 typedef int _bool; typedef struct Link_Node{ int data; struct Link_Node* next; }Link_Node,*Link_List; _bool InitList(Link_List* L);//初始化链表,有头结点 _bool Insert(Link_List* L,int x,int y);//将y插入在链表L中值为x的节点之前,如无值为x的节点则把y插入到表尾部 Link_Node* Find_Front_Node(Link_List* L,int x);//在链表L中找出值为x的节点的前一个节点,若无值为x的节点则返回该链表最后一个节点 _bool Delete(Link_List* L,int x);//将删除链表L中第一个值为x的节点,若无值为x的节点则不删除 void List_Print(Link_List* L);//打印链表 int main(void){ Link_List L; InitList(&L); char str[6];//用于存储题目中的操作名称 int n = 0;//存储操作次数 //题目里的x和y int x = 0; int y = 0; scanf("%d",&n); while(n){ scanf("%s",str); if(strcmp(str,"insert") == 0){ scanf("%d %d",&x,&y); Insert(&L,x,y); // List_Print(&L); } else if(strcmp(str,"delete") == 0){ scanf("%d",&x); Delete(&L,x); } n--; } List_Print(&L); return 0; } _bool InitList(Link_List* L){ (*L) = (Link_Node*)malloc(sizeof(Link_Node)); (*L)->next = NULL; return true; } _bool Insert(Link_List* L,int x,int y){ Link_Node* p = Find_Front_Node(&(*L),x); Link_Node* s = (Link_Node*)malloc(sizeof(Link_Node)); s->data = y; s->next = p->next; p->next = s; return true; } Link_Node* Find_Front_Node(Link_List* L,int x){ Link_Node* p = (*L); Link_Node* r = (*L)->next; while(r != NULL){ if(r->data == x){ break; } p = r; r = r->next; } return p; } _bool Delete(Link_List* L,int x){ Link_Node* p = Find_Front_Node(&(*L),x); if(p->next == NULL){ return true; } else{ p->next =p->next->next; return true; } } void List_Print(Link_List* L){ Link_Node* p = (*L); if(p->next == NULL){ printf("NULL\n"); return; } p = p->next; while(p != NULL){ printf("%d ",p->data); p = p->next; } }