题解 | #HJ48 从单向链表中删除指定值的节点#
从单向链表中删除指定值的节点
http://www.nowcoder.com/practice/f96cd47e812842269058d483a11ced4f
#include <stdio.h>
#include <stdlib.h>
typedef struct tLinkNode {
int data;
struct tLinkNode *next;
} LinkNode;
int main() {
int n, v;
scanf("%d%d", &n, &v);
LinkNode * head = (LinkNode*)malloc(sizeof(LinkNode));
LinkNode * tail = head;
LinkNode * temp;
head->data = v;
head->next = NULL;
// 插入n-1个点
int first, secend;
for(int i = 0; i<n-1; i++) {
scanf("%d%d", &first, &secend);
tail = head;
while (tail) {
if (tail->data == secend) {
temp = (LinkNode*)malloc(sizeof(LinkNode));
temp->data = first;
temp->next = tail->next;
tail->next = temp;
break;
}
tail = tail->next;
}
}
// 待删除结点
int toDelete;
scanf("%d", &toDelete);
// 首节点特殊处理
if (head->data == toDelete) {
temp = head->next;
free(head);
head = temp;
} else {
tail = head;
while (tail->next) {
if (tail->next->data == toDelete) {
temp = tail->next->next;
free(tail->next);
tail->next = temp;
}
tail = tail->next;
}
}
// 打印输出
tail = head;
while(tail) {
printf("%d ", tail->data);
tail = tail->next;
}
return 0;
}