题目:删除链表中的指定元素
描述:给定一个单链表的头节点 head
和一个目标值 target
,请删除链表中所有等于目标值的节点,并返回删除后的链表头节点。
要求:需要原地删除节点,即不使用额外的数据结构。
示例:
输入:1 -> 2 -> 3 -> 2 -> 4,目标值为 2
输出:1 -> 3 -> 4
#include<stdio.h>
#include<stdlib.h>
typedef int elemtype;
typedef struct lnode
{
elemtype data;
struct lnode* next;
} lnode, * linklist;
void creat(linklist* head)
{
int k;
scanf_s("%d", &k);
linklist a, s;
a = (linklist)malloc(sizeof(lnode));
a->next = NULL;
*head = a;
while (k != -1)
{
s = (linklist)malloc(sizeof(lnode));
s->data = k;
s->next = a->next;
a->next = s;
scanf_s("%d", &k);
}
}
void deleteTarget(linklist head, int target)
{
linklist p, q;
q = head;
p = head->next;
while (p != NULL)
{
if (p->data == target)
{
q->next = p->next;
linklist tmp = p;
p = p->next;
free(tmp);
}
else
{
q = p;
p = p->next;
}
}
}
void printList(linklist head)
{
linklist p = head->next;
while (p != NULL)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main()
{
linklist head = NULL;
int num = 2;
creat(&head);
deleteTarget(head, num);
printList(head);
return 0;
}