题解 | 【模板】链表
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include <stdio.h>
#include <stdlib.h>
typedef struct lian {
int data;
struct lian* next;
} lian;
lian* create() {
lian* new = (lian*)malloc(sizeof(lian));
// new.data=data;
new->next = NULL;
return new;
}
lian* insert(lian* head, int x, int y) {
lian* a = create();
a->data = y;
lian* temp = head;
lian* pre = NULL;
if (head == NULL) {
//head ->data= y;
return a;
}
if(head->data==x){
head=a;
a->next=temp;
return head;
}
while (temp != NULL && temp->data != x) {
pre = temp;
temp = temp->next;
}
if (temp != NULL) {
pre->next = a;
a->next = temp;
}
if (temp == NULL) {
pre->next = a;
}
return head;
}
lian* delete (lian* head, int x) {
lian* temp = head;
lian* pre = NULL;
if (head == NULL) {
return head;
}
if(head->data==x){
head=head->next;
return head;
}
while (temp->data != x&&temp!=NULL) {
pre=temp;
temp = temp->next;
}
if(temp!=NULL){
pre->next=temp->next;
free (temp);
}
return head;
}
int main() {
int n;
int x, y;
char s[6];
scanf("%d", &n);
lian* head = NULL;
for (int i = 0; i < n; i++) {
scanf("%s", s);
if (s[0] == 'i') {
scanf("%d %d", &x, &y);
head=insert(head, x, y);
}
if (s[0] == 'd') {
scanf("%d", &x);
head=delete (head, x);
}
}
lian* temp = head;
lian* next=NULL;
if (head== NULL) {
printf("NULL");
} else {
while (temp != NULL) {
printf("%d ", temp->data);
next=temp->next;
free(temp);
temp=next;
}
}
return 0;
}
查看10道真题和解析