#include <stdio.h> #include <stdlib.h> //手撕链表 typedef int DateType; typedef struct List { DateType val; struct List* next; }LT; //返回新节点 LT* CreateBayNode(DateType x) { LT* newnode=(LT*)malloc(sizeof(LT)); if(newnode==NULL) { perror("newnode malloc fail"); return NULL; } newnode->next=NULL; newnode->val=x; return newnode; } //尾插 void PushBank(LT** head,DateType x) { //创建要插入的节点 LT* newnode = CreateBayNode(x); //判断头节点是否为NULL if(*head==NULL) { *head=newnode; } else { //进行找尾 LT* cur=*head; LT* tail=*head; while(cur) { tail=cur; cur=cur->next; } //进行连接 tail->next=newnode; } } //打印 void ListPrint(LT* head) { LT* cur=head; while(cur) { printf("%d ",cur->val); cur=cur->next; } } LT* new=NULL; //将不等于x的节点尾插到新链表 void PushNew(LT* A,DateType x) { LT* cur=A; while(cur) { if(cur->val!=x) { PushBank(&new, cur->val); } cur=cur->next; } } int main() { int n=0; int x=0; scanf("%d %d",&n,&x); int arr[n]; for(int i=0;i<n;i++) { scanf("%d",&arr[i]); } LT* A=NULL; //插入链表 for(int i=0;i<n;i++) { PushBank(&A,arr[i]); } PushNew(A,x); ListPrint(new); return 0; }
将数组元素尾插到一个链表
再将该链表中不等于x值的节点尾插到新链表中
最后将新链表打印即可