当前位置:编程学习 > C/C++ >>

帮调c++链表程序

我写的程序如下:

#include <iostream>
#define null NULL
using namespace std;

struct node
{
int data;
struct node * next;
};

node * create(int n)
{
node * head, * s;
head = null;

int i = 0, x;

while ( i < n)
{
s = new node;
cin >> x;
s->data = x;
s->next = head;
head = s;

i++;
}
return head;
}

void show(node * head)
{
node * p;
p = head;
while ( p != null)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}

void deletes(node * head)
{
node * p, * s;
p = new node;
p = null;
p->next = head ;
while (p->next != null)
{
if (p->next->data > 9)
{
s = p->next ;
p->next = s->next ;
free(s);
}
p = p->next ;
}

}

void main()
{
node * m;
m = create(5);
show(m);
deletes(m);
show(m);
}
程序想要实现输入5个整数,用链表逆向显示出来,同时删除数据元素大于9的数,在调试过程中,deletes函数有点问题,按照我上面写的,在deletes函数中的head指向的是第一个数(并非NULL),如果待删除的元素是head指向的第一个数时,这个数如何删除? 比如:你输入数据:12 1 34 5 67
按理说结果是:67 5 34 1 12
5 1,谁能帮忙调试一下?
答案:#include &lt;iostream&gt;
#define null 0
using namespace std;
struct node
{
int data;
struct node *next;
};
node * create(int n)
{
node *head, *s;
head =null;
int i=0,x;
while (i&lt;n)
{
s= new node;
cin &gt;&gt;x;
s-&gt;data=x;
s-&gt;next=head;
head=s;
i++;
}
return head;
}
void show(node *head)
{
node *p;
p=head;
if(head==null)
{
cout&lt;&lt;"链表为空"&lt;&lt;endl;

exit(1);
}
while (p!=null)
{
cout &lt;&lt;p-&gt;data&lt;&lt;" ";
p=p-&gt;next;
}
cout&lt;&lt;endl;
}
node* deletes(node * head)
{
node *p,*s;

s=p=head;
while(s!=null)
if(s-&gt;data&gt;9)
{
if(head==s)
{

head=p-&gt;next;

s=s-&gt;next;

p=p-&gt;next;
}

else

{

p-&gt;next=s-&gt;next;

if(s-&gt;next==null)

s=null;

else


s=s-&gt;next;

}
}
else
{

if(p!=s)


p=p-&gt;next;

s=s-&gt;next;
}
return head;
}
void main()
{
node * m;
m = create(5);
show(m);
m=deletes(m);
show(m);
}

我给改好了,你自己看看,逻辑关系挺复杂的。

上一个:c++的问题??
下一个:C++怎么编计算器

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,