链表问题
最近刚学链表,写了这个代码,但并没有发现输出,有没有人帮忙看看啊,谢了。代码目标是在一个链表中,按照从小到大顺序,插入一个节点。
#include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
typedef struct Node
{
int data;
struct Node*pNext;
}node,*pnode;
pnode creatnode()
{
int num,i,b,val;
pnode phead=(pnode)malloc(sizeof(Node));
//printf("输入多少个节点:");
scanf("%d",&num);
pnode tail=phead;
tail->pNext=NULL;
for(i=0;i<num;i++)
{
pnode pnew=(pnode)malloc(sizeof(Node));
// printf("第%d个结点值为:",i+1);
scanf("%d",&val);
pnew->data=val;
tail->pNext=pnew;
tail=pnew;
tail->pNext=NULL;
}
return phead;
}
int print(pnode phead)
{
pnode p=phead;
while((p->pNext)!=NULL)
{
p=p->pNext;
cout<<p->data<<" ";
}
return 0;
}
int del(pnode phead)
{
pnode p=phead,n=phead;
while((p)!=NULL)
{
delete p;
n=n->pNext;
p=n;
}
}
int arrange(pnode phead,pnode newnode)
{
pnode p=phead;
pnode n;
pnode zj;
while((p->pNext)!=NULL)
{
if(((p->data)<=(newnode->data))&&((p->pNext->data)>(newnode->data)))
{
zj=p->pNext;
p->pNext=newnode;
newnode->pNext=zj;
break;
}
p=p->pNext;
}
return 0;
}
int main()
{
pnode phead;
phead=creatnode();
pnode newnode=(pnode)malloc(sizeof(Node));
scanf("%d",newnode->data);
arrange(phead,newnode);
print(phead);
del(phead);
return 0;
}
这只是一个开始 #include <iostream>
#include <stdio.h>
#include <malloc.h>
using namespace std;
struct Node
{
int data;
Node* pNext;
};
Node* Creatnode()
{
int num, i=1;
Node* phead = (Node*)malloc(sizeof(Node));
Node* tail = phead;
printf("输入多少个节点:");
scanf("%d", &num);
printf("第%d个结点值为:", i);
scanf("%d", &(phead->data));
for (i = 2; i<=num; i++)
{
Node* pnew = (Node*)malloc(sizeof(Node));
printf("第%d个结点值为:",i);
scanf("%d", &(pnew->data));
tail->pNext = pnew;
tail = pnew;
tail->pNext = NULL;
}
return phead;
}
void print(Node* phead)
{
Node* p = phead;
while (p->pNext != NULL)
{
cout << p->data << " ";
p = p->pNext;
}
cout << p->data << endl;
}
void del(Node* phead)
{
Node *p = phead, *n = phead;
while (n->pNext != NULL)
{
p = n;
n = n->pNext;
delete p;
}
}
void arrange(Node* phead, Node* newnode)
{
Node* p = phead;
Node* zj;
while (p->pNext != NULL)
{
if (((p->data) <= (newnode->data)) && ((p->pNext->data)>(newnode->data)))
{
zj = p->pNext;
p->pNext = newnode;
newnode->pNext = zj;
break;
}
p = p->pNext;
}
if (p->pNext == NULL)
{
p->pNext = newnode;
newnode->pNext = NULL;
}
}
int main()
{
Node* phead;
phead = Creatnode();
Node* newnode = (Node*)malloc(sizeof(Node));
printf("输入要插入的数\n");
scanf("%d", &newnode->data);
arrange(phead, newnode);
print(phead);
del(phead);
return 0;
}
页:
[1]