题解 | 从单向链表中删除指定值的节点
从单向链表中删除指定值的节点
https://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f?tpId=37&tqId=21271&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26pageSize%3D50%26search%3D%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=
#include <stdio.h> #include <stdlib.h> #include <string.h> //单链表结点结构体 typedef struct ListNode { int data; struct ListNode* next; } ListNode, *List ; //删除节点 void del_List(List* l,int del_val) { List q ; List p = *l; while(p->next != NULL){ if(p->next->data == del_val){ q = p->next; p->next = q->next; free(q); } p = p->next; } } //插入节点 List insert_list(List* l, int n1, int n2) { //printf("%p\n",l); ListNode* p = (ListNode*)malloc(sizeof(ListNode)); p->data = n1; p->next = NULL; ListNode* q = *l; while (q != NULL) { if (q->data == n2) { p->next = q->next; q->next = p; } q = q->next; } return *l; } int main() { char s[10000];//存储输入的字符串 char num[5];//存储strtok分解的字符串 int i, j = 0; //遍历字符串 int a ;//存储分解出的字符串数字转换成十进制数字 int count[1005] = {0}; char* token = NULL; char ch[] = {' ', '\n'}; fgets(s, sizeof(s), stdin);//fgets读取到换行符截止 token = strtok(s, ch);//找到字符串中的ch处替换成‘\0’ while (token != NULL) { a = 0; for (i = 0; i < strlen(token); i++) { num[i] = token[i]; } num[i] = '\0'; for (i = 0; i < strlen(num); i++) { a = a * 10 + num[i] - '0'; } count[j] = a; j++; token = strtok(NULL, ch); } ListNode* head = (ListNode*)malloc(sizeof(ListNode)); head->data = count[1]; head->next = NULL;//初始化头节点 for (i = 2; i < j - 2; i += 2) { insert_list(&head, count[i], count[i + 1]); } del_List(&head,count[j - 1]); ListNode* q = head; while(q != NULL){ printf("%d ", q->data); q = q->next; } return 0; }
C语言编程练习 文章被收录于专栏
菜鸟使用C语言的方法完成华为od练习题的过程