3584 - 线性链表的删除
时间限制 : 1 秒
内存限制 : 128 MB
输入一个正整数序列,遇负数时停止,建立一个线性链表存储读入的数据,然后从键盘读入一数据x,在该链表中删除比x大的数据后输出。
题目输入
题目输出
输入/输出样例
输入格式
1 2 3 4 5 -1 3
输出格式
1 2 3
C语言解答
#include<stdio.h> #include<stdlib.h> typedef struct tagNODE { int data; struct tagNODE *next; }node,*linklist; void linkcreat(linklist *head) { linklist temp,upd; int buffer; (*head)=(linklist)malloc(sizeof(node)); (*head)->next=NULL; upd=(*head); scanf("%d",&buffer); while(buffer>0) { temp=(linklist)malloc(sizeof(node)); temp->next=NULL; upd->next=temp; temp->data=buffer; upd=temp; scanf("%d",&buffer); } } void linkdelet(linklist head,int x) { linklist temp,val; temp=head; while(temp->next!=NULL) { if(temp->next->data>x) { val=temp->next; temp->next=temp->next->next; free(val); val=NULL; continue; } if(temp->next!=NULL) temp=temp->next; } } void linkput(linklist head) { linklist temp; temp=head; while(temp->next!=NULL) { temp=temp->next; printf("%d ",temp->data); } } int main() { int x; linklist temp,head; linkcreat(&head); scanf("%d",&x); linkdelet(head,x); linkput(head); return 0; }
C++解答
#include<bits/stdc++.h> using namespace std; struct node{ int data; node *next; }; void Print(node *h){ node *x = h->next; while(x!=NULL){ cout<<x->data<<" "; x = x->next; } } void Delete(node *h,int val){ node *x = h,*y; while(x!=NULL){ if(x->next!=NULL&&x->next->data>val){ y = x->next; x->next = y->next; delete y; } else{ x = x->next; } } } int main() { node *h,*p,*r; h = new node; h->next = NULL; r = h; int x; while(cin>>x&&x!=-1){ p = new node; p->data = x; p->next = NULL; r->next = p; r = p; } cin>>x; Delete(h,x); Print(h); return 0; }