题解 | #AB9 【模板】链表#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
C语言版本
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct tLinkNode {
int data;
struct tLinkNode *next;
} LinkNode;
bool searchPrev(LinkNode *pLinkList, int x, LinkNode **p) {
LinkNode *t = pLinkList;
while (t->next) {
if (t->next->data == x) {
*p = t;
return true;
}
t = t->next;
}
*p = t;
return false;
}
bool insert(LinkNode *pLinkList, int x, int y) {
LinkNode *pPrev = NULL;
searchPrev(pLinkList, x, &pPrev);
LinkNode *pNewNode = (LinkNode*)malloc(sizeof(LinkNode));
pNewNode->data = y;
pNewNode->next = pPrev->next;
pPrev->next = pNewNode;
return true;
}
bool delete(LinkNode *pLinkList, int x) {
LinkNode *pPrev = NULL;
searchPrev(pLinkList, x, &pPrev);
if (pPrev == NULL || pPrev->next == NULL) {
return false;
} else if (pPrev->next != NULL) {
LinkNode *p = pPrev->next->next;
free(pPrev->next);
pPrev->next = p;
}
return true;
}
int main() {
int n, x, y;
char s[10];
scanf("%d", &n);
LinkNode *pLinkList = (LinkNode*)malloc(sizeof(LinkNode));
pLinkList->next = NULL;
while(n--) {
scanf("%s", s);
if (strcmp(s, "insert") == 0) {
scanf("%d%d", &x, &y);
insert(pLinkList, x, y);
} else if (strcmp(s, "delete") == 0) {
scanf("%d", &x);
delete(pLinkList, x);
}
}
LinkNode *p = pLinkList;
if (p->next == NULL) {
printf("NULL");
}
while (p->next) {
p = p->next;
printf("%d ", p->data);
}
return 0;
}