链表节点定义为: struct Node{ int data; struct Node *next; }
编程实现:输入一个正整数 repeat (0<repeat<10),做 repeat 次下列运算: 输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的奇数值结点删除后输出
输入输出示例:括号内为说明
2 (repeat=2) 1 2 3 4 5 6 7 -1 1 3 5 -1
2 4 6
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Node { int data; struct Node *next; }No; No* createlist() { No * head=NULL; No * p=NULL,* pre=NULL; int a=0; head=(No*)malloc(sizeof(No)); head->next=NULL; pre=head; scanf("%d",&a); if(a==-1) { return NULL; } else { p=(No*)malloc(sizeof(No)); p->data=a; pre->next=p; pre=p; } while(scanf("%d",&a)){ if(a!=-1) { p=(No*)malloc(sizeof(No)); p->data=a; pre->next=p; pre=p; } else { pre->next=NULL; break; } } return (head); } No* del(No*head) { No* temp; No* q=head; No* h=head->next; while(h) { if((h->data)%2!=0) { q->next=h->next; } else{ q=q->next; }h=h->next; } return (head); } void print(No*head) { while(head->next->next) { printf("%d ",head->next->data); head=head->next; } printf("%d\n",head->next->data); } int main() { int n,i; scanf("%d",&n); for(i=0;i<n;i++){ No*p; p=(No*)malloc(sizeof(No)); p=createlist(); if(p!=NULL) { p=del(p); print(p); } } return 0; }
程序试过,输入输出都和例子一样,没啥问题,然而提交到系统总是显示段错误。
杰伦窗外的小麻雀