数据结构C++()填空题

有一个单链表的第一个结点指针为head,编写一个函数将该单链表逆置,即最后一个结点变成第一个结点,原来倒数第二个结点变成第二个结点。在逆置中不能建立新的单链表(根据题目填空完善程序)
#include <stdio.h>
#include <malloc.h>
#define NULL 0
typedef int elemtype;
typedef struct linknode
{
elemtype data;
struct linknode *next;
}nodetype;

nodetype *create()
{
elemtype d;
nodetype *h,*s,*t;
int i=1;
h=NULL;
printf("建立一个单链表\n");
while (1)
{
printf("输入第%d节点data域值:",i);
scanf("%d",&d);
if (d==0)_________(1)____; /*以0表示输入结束*/
if(i==1) /*建立第一个结点*/
{
h=________(2)_____;
h->data=d;h->next=NULL;t=h;
}
else
{
s=(nodetype *)malloc(sizeof(nodetype));
s->data=d;s->next=NULL;t->next=s;
__(3)______; /*t始终指向生成的单链表的最后一个结点*/
}
i++;
}
return h;
}
void disp(nodetype *h)
{
nodetype *p=h;
printf("输出一个单链表:\n");
if (p==NULL) printf("空表");
while (p!=NULL)
{
printf("%d",p->data); _______(4)___;
}
printf("\n");
getch();
}

int len(nodetype *h)
{
int i=0;
nodetype *p=h;
while (p)
{i++;p=p->next;}
return(i);
}

nodetype *invert(nodetype *h)
{
nodetype *p,*q,*r;
if (len(h)<=1)
{printf("逆置的单链表至少有2个节点\n");
return(NULL);
}
else
{p=h;q=p->next;
while (q!=NULL)
{r=q->next;
q->next=p;
p=q;q=r;
}
h->next=NULL;
h=p;
return h;
}
}

void main()
{
nodetype *head;
head=create();
disp(head);
head=invert( _______(5)________);
disp(head);
}
建立一个单链表
输入第1个节点data 域的值:1
输入第2个节点data 域的值:2
输入第3个节点data 域的值:3
输入第4个节点data 域的值:4
输入第5个节点data 域的值:5
输入第6个节点data 域的值:0
输出一个单链表:_______(6)___________
________(7)__________

#include <stdio.h>
#include <malloc.h>
#define NULL 0
typedef int elemtype;
typedef struct linknode
{
elemtype data;
struct linknode *next;
}nodetype;

nodetype *create()
{
elemtype d;
nodetype *h,*s,*t;
int i=1;
h=NULL;
printf("建立一个单链表\n");
while (1)
{
printf("输入第%d节点data域值:",i);
scanf("%d",&d);
if (d==0)break; /*以0表示输入结束跳出循环,如果return NULL,怎么生成头结点*/
if(i==1) /*建立第一个结点*/
{
h=(nodetype*)malloc(sizeof(nodetype));
h->data=d;h->next=NULL;t=h;
}
else
{
s=(nodetype *)malloc(sizeof(nodetype));
s->data=d;t->next=s;//注意 应该没有s->next=NULL;
t=s; /*t始终指向生成的单链表的最后一个结点*/
}
i++;
}
t->next=NULL;//加上这一条。
return h;
}
void disp(nodetype *h)
{
nodetype *p=h;
printf("输出一个单链表:\n");
if (p==NULL) printf("空表");
while (p!=NULL)
{
printf("%d",p->data); p=p->next;
}
printf("\n");
getch();
}

int len(nodetype *h)
{
int i=0;
nodetype *p=h;
while (p)
{i++;p=p->next;}
return(i);
}

nodetype *invert(nodetype *h)
{
nodetype *p,*q,*r;
if (len(h)<=1)
{printf("逆置的单链表至少有2个节点\n");
return(NULL);
}
else
{p=h;q=p->next;
while (q!=NULL)
{r=q->next;
q->next=p;
p=q;q=r;
}
h->next=NULL;
h=p;
return h;
}
}

void main()
{
nodetype *head;
head=create();
disp(head);
head=invert(head);
disp(head);
}
/*
建立一个单链表
输入第1个节点data 域的值:1
输入第2个节点data 域的值:2
输入第3个节点data 域的值:3
输入第4个节点data 域的值:4
输入第5个节点data 域的值:5
输入第6个节点data 域的值:0
输出一个单链表:
12345
输出一个单链表:
54321
*/
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-04
1 return NULL;
2 (nodetype *)malloc(sizeof(nodetype));
3 t=s;
4 p=p->next;
5 head
6 输出一个单链表:
7 123450
相似回答