题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct no{
int data;
struct no *next;
}ListNode;
ListNode*removeElem(int x);
void STLPrint(ListNode*ps);
void STLinsert(ListNode**ps,int x,int y);
void STLdelet(ListNode**ps,int x);
int main()
{
ListNode*head = NULL;
int s1,s2,s3;
char input[10]={0};
int count = 0;
scanf("%d",&count);
while(count--)
{
scanf("%s",input);
if(strcmp(input,"insert")==0)
{
scanf("%d%d",&s1,&s2);
STLinsert(&head,s1,s2);
}
else if(strcmp(input,"delete")==0)
{
scanf("%d",&s3);
STLdelet(&head,s3);
}
}
STLPrint(head);
}
ListNode*removeElem(int x)
{
ListNode*newNode = (ListNode*)malloc(sizeof(ListNode));
if(newNode==NULL)
{
perror("malloc");
exit(-2);
}
newNode->data = x;
newNode->next = NULL;
return newNode;
}
void STLPrint(ListNode*ps)
{
ListNode*cur = ps;
if(ps==NULL)
{
printf("NULL");
}
while(cur)
{
printf("%d ",cur->data);
cur = cur->next;
}
}
void STLinsert(ListNode**ps,int x,int y)
{
ListNode*cur = *ps;
ListNode*prev = NULL;
while(cur)
{
if(cur->data==x)
break;
prev = cur;
cur = cur->next;
}
if(!prev)
{
ListNode*newNode = removeElem(y);
newNode->next = *ps;
*ps = newNode;
}
else{
ListNode*newNode = removeElem(y);
prev->next = newNode;
newNode->next = cur;
}
}
void STLdelet(ListNode**ps,int x)
{
ListNode*cur = *ps;
ListNode*prev = NULL;
while(cur&&cur->data!=x)
{
prev = cur;
cur = cur->next;
}
if(cur==NULL)
{
return;
}
if(prev==NULL)
{
*ps = cur->next;
}
else{
prev->next = cur->next;
}
free(cur);
}
迅雷公司福利 193人发布