题解 | 牛牛的链表删除
牛牛的链表删除
https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f
#include <stdio.h> #include <stdlib.h> // write your code here...... // 节点结构体 typedef struct Node { int data; struct Node* next; }Node; //将数组转换为链表 Node* creatlist(int *arr, int n) { Node* head = NULL; Node* tail = NULL; if(n==0) { return NULL; } //创建新节点 for(int i=0; i<n;i++) { Node* newnode = (Node*)malloc(sizeof(Node)); newnode->data=arr[i]; newnode->next= NULL; if(head==NULL) { head = newnode; tail = newnode; }else { tail->next = newnode; tail = newnode; } } return head; } void freelist(Node* head) { Node* current = head; while(current!=NULL) { Node* temp=current; current = current->next; free(temp); } } //打印链表 void printList(Node* head) { Node* current = head; if(current == NULL) { printf("The list is empty.\n"); return; } while(current!=NULL) { printf("%d",current->data); if(current->next!=NULL) { printf(" "); } current = current ->next; } printf("\n"); } int main() { int n,x; scanf("%d%d",&n,&x); int* arr=(int*)malloc(n*sizeof(int)); for (int i = 0; i < n; i++) { scanf("%d",&arr[i]); } // write your code here...... Node* head = creatlist(arr, n); while(head!=NULL&&head->data==x) { Node* temp = head; head = head->next; free(temp); } Node* current = head; while(current!=NULL&¤t->next!=NULL) { if(current->next->data==x) { Node* temp = current->next; current->next=current->next->next; free(temp); }else { current = current->next; } } //3.打印删除后的链表 printList(head); //4.释放资源 free(arr); freelist(head); return 0; }
考察要点:1.数组转链表 2. 利用头指针打印链表 3. 条件判断头部和中间节点是X的情况如何用代码表达出来,
疑问:在判断头部节点情况时直接使用head!=NULL&&head->data ==x;而在判断中间或者尾部节点时Node* current = head;
直接操作 head:是为了处理 “入口节点” 需要被删除的特殊情况。因为这会改变整个链表的起点。
引入 current 辅助指针:是在 “入口节点” 安全后,用它来遍历和修改链表的 “内部节点”。此时 head 作为链表的总入口地址,必须保持不变,所以我们不能再动它,而是用一个复制品 current 去“冒险”。