题解 | 牛牛的链表删除
牛牛的链表删除
https://www.nowcoder.com/practice/d3df844baa8a4c139e103ca1b1faae0f
#include <stdio.h>
#include <stdlib.h>
#define N 100
struct Node
{
int data;
struct Node *next;
};
struct Node* createList(int *arr,int n)
{
struct Node *head = NULL, *tail = NULL;
for(int i = 0; i < n; i++)
{
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode -> data = arr[i];
newNode -> next = NULL;
if(head == NULL)
{
head = newNode;
tail = newNode;
}
else
{
tail -> next = newNode;
tail = newNode;
}
}
return head;
}
struct Node* deleteNode(struct Node *head,int x)
{
//处理表头是x的情况
while(head != NULL && head -> data == x)
{
struct Node *temp = head;
head = head -> next;
free(temp);
}
struct Node *p = head;
while(p != NULL && p -> next != NULL)
{
if(p -> next -> data == x)
{
struct Node *temp = p -> next;
p -> next = p -> next -> next;
free(temp);
}
else{
p = p -> next;
}
}
return head;
}
void printList(struct Node *head)
{
struct Node *p = head;
while(p != NULL)
{
printf("%d ",p -> data);
p = p -> next;
}
}
int main()
{
int n,x;
scanf("%d %d",&n,&x);
int arr[N];
for(int i = 0; i < n; i++)
{
scanf("%d",&arr[i]);
}
struct Node *head = createList(arr,n);
head = deleteNode(head, x); // 删除值为x的节点
printList(head);
return 0;
}
