题目要求:
我的代码实现(两种):
(1)基于头插法所构造的单链表:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
typedef struct LNode{
ElemType data;
struct LNode* next;
}LNode,*LinkList;
//头插法(有头结点)
LinkList List_HeadInsert(LinkList &L)
{
ElemType x;
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
LNode *s;
scanf("%d",&x);
while(x!=9999)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;
L->next=s;
scanf("%d",&x);
}
return L;
}
//本题的解答:
void ReversePrint(LinkList &L)
{
LNode *p=L,*q;
for(;p->next!=NULL;p=p->next);
while(L->next!=p)
{
q=L->next;
L->next=q->next;
q->next=p->next;
p->next=q;
}
for(q=L->next;q;q=q->next)printf("%d ",q->data);
printf("\n");
return;
}
//................................
//彻底销毁整个链表
void DestroyList(LinkList &L)
{
LNode *p=L->next,*q;
while(p)
{
q=p;
p=p->next;
free(q);
}
free(L);
return;
}
int main()
{
LinkList L;
printf("\n构造带头结点的单链表L:\n");
L=List_HeadInsert(L);
printf("反转输出链表:\n");
ReversePrint(L);
DestroyList(L);
return 0;
}
(2)基于尾插法所构造的单链表:
#include<stdio.h>
#include<stdlib.h>
#define ElemType int
typedef struct LNode{
ElemType data;
struct LNode* next;
}LNode,*LinkList;
//尾插法(有头结点)
LinkList List_HeadInsert(LinkList &L)
{
ElemType x;
L=(LNode*)malloc(sizeof(LNode));
L->next=NULL;
LNode *r=L,*s;
scanf("%d",&x);
while(x!=9999)
{
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=NULL;
r->next=s;
r=s;
scanf("%d",&x);
}
return L;
}
//本题的解答:
void ReversePrint(LinkList &L)
{
LNode *p=L,*q;
for(;p->next!=NULL;p=p->next);
while(L->next!=p)
{
q=L->next;
L->next=q->next;
q->next=p->next;
p->next=q;
}
for(q=L->next;q;q=q->next)printf("%d ",q->data);
printf("\n");
return;
}
//................................
//彻底销毁整个链表
void DestroyList(LinkList &L)
{
LNode *p=L->next,*q;
while(p)
{
q=p;
p=p->next;
free(q);
}
free(L);
return;
}
int main()
{
LinkList L;
printf("\n构造带头结点的单链表L:\n");
L=List_HeadInsert(L);
printf("反转输出链表:\n");
ReversePrint(L);
DestroyList(L);
return 0;
}
在反转单链表这方面使用了类似于头插法的算法思想;