简单的单向链表

C++语言 码拜 9年前 (2015-05-11) 1556次浏览 0个评论
 

链表节点定义为:
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<iostream>
#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct Node) 
using namespace std;
struct Node{
int data;
struct Node *next;

};
int n;

int main()
{

int i=0;
int repeat;
struct Node *head,*p1,*p2;
cin>>repeat;

for(i=0;i<repeat;i++)
{
n=0;//下面判断用 
int m=0;//下面判断用 
p1=p2=(struct Node *)malloc(LEN);//开辟新单元 
cin>>p1->data;
head=NULL;
while(p1->data!=-1)
{
n++;
if(n==1)head=p1;
else p2->next=p1;
p2=p1;
p1=(struct Node*)malloc(LEN);
cin>>p1->data;
if((p1->data)%2==0) //判断 
{
if(m==0)
{
cout<<p1->data;m++;
}
else cout<<” “<<p1->data; //这里的首个无法判断,怎么做??比如2 4 -1 输出的是4 
}

}
cout<<endl;

}

return 0;
}

35分
修改如下:

#include<stdlib.h>
#include<string.h>
#define LEN sizeof(struct Node) 
using namespace std;
typedef struct Node 
{
	int data;
	struct Node *next;
}Node;
Node *createList()
{
	int data;
	Node *head = (Node*)malloc(LEN);
	Node *p = head;
	while (scanf("%d", &data) && -1 != data)
	{
		p->next= (Node*)malloc(LEN);
		p = p->next;
		p->data = data;
	}
	p->next = NULL;
	return head;
}
Node *deleteOddNode(Node *head)
{
	Node *p, *q;
	p = head;
	q = head->next;
	do
	{
		if (q->data % 2)
		{
			p->next = q->next;
			free(q);
			q = p->next;
		}
		else
		{
			p = q;
			q = q->next;
		}
	} while (q);
	return head;
}
void printList(Node *head)
{
	Node *p = head->next;
	while (p)
	{
		printf("%2d", p->data);
		p = p->next;
	}
}
int repeat;
int main(void)
{
	scanf("%d", &repeat);
	Node *head;
	while (repeat--)
	{
		head = createList();
		head = deleteOddNode(head);
		printList(head);
		printf("\n");
	}
	return 0;
}
//2
//1 2 3 4 5 6 7 -1
// 2 4 6
//1 3 5 7 -1
//
5分
楼上这改得也太多了,其实,楼主只需要把判断语句移动到while一进来做就可以了,因为你输入了两次,才做第一次判断。
引用 2 楼 Idle_Cloud 的回复:

楼上这改得也太多了,其实,楼主只需要把判断语句移动到while一进来做就可以了,因为你输入了两次,才做第一次判断。

题意是:“建立一个单向链表,将其中的奇数值结点删除后输出”先建链表,再删除节点,后输出


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明简单的单向链表
喜欢 (0)
[1034331897@qq.com]
分享 (0)

文章评论已关闭!