编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; }
输入输出示例:括号内为说明
输入样例:
1 2 3 4 5 6 7 -1
输出样例:
1 3 5 7
编程实现:输入若干个正整数(输入-1为结束标志),建立一个单向链表,将其中的偶数值结点删除后输出。链表节点定义为: struct Node{ int data; struct Node *next; }
输入输出示例:括号内为说明
输入样例:
1 2 3 4 5 6 7 -1
输出样例:
1 3 5 7
#include "stdio.h"
#include "stdlib.h"
typedef struct Node { int data; struct Node *next; } LList;
int main()
{
LList * header = NULL;
Node * p;
while (true)
{
int input;
scanf("%d", &input);
if (input == -1) break;
if (!header)
{
header = (Node *)malloc(sizeof(Node));
p = header;
header->data = input;
header->next = NULL;
}
else
{
p->next = (Node *)malloc(sizeof(Node));
p = p->next;
p->data = input;
p->next = NULL;
}
}
p = header;
Node * preP = NULL;
while (p)
{
if (p->data % 2 == 0)
{
Node * temp;
if (!preP)
{
temp = header;
header = header->next;
p = header;
free(temp);
}
else
{
temp = p;
p = p->next;
preP->next = p;
free(temp);
}
}
preP = p;
p = p->next;
}
p = header;
int i = 0;
while (p)
{
printf("%d ", p->data);
p = p->next;
}
printf("\n");
return 0;
}