帮调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 <iostream>
#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<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;
if(head==null)
{
cout<<"链表为空"<<endl;
exit(1);
}
while (p!=null)
{
cout <<p->data<<" ";
p=p->next;
}
cout<<endl;
}
node* deletes(node * head)
{
node *p,*s;
s=p=head;
while(s!=null)
if(s->data>9)
{
if(head==s)
{
head=p->next;
s=s->next;
p=p->next;
}
else
{
p->next=s->next;
if(s->next==null)
s=null;
else
s=s->next;
}
}
else
{
if(p!=s)
p=p->next;
s=s->next;
}
return head;
}
void main()
{
node * m;
m = create(5);
show(m);
m=deletes(m);
show(m);
}
我给改好了,你自己看看,逻辑关系挺复杂的。
上一个:c++的问题??
下一个:C++怎么编计算器