数据结构严蔚敏版的相关算法实操
链表逆置
定义相关常量和结构体类型
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASALBE -1
#define OVERFLOW -2
#define LIST_INIT_SIZE 10
#define LISTINCREMENT 10
typedef struct Word{
char word;
}ElemType;
typedef struct Lnode{
ElemType data;
struct Lnode *next;
}LNode,*LinkList;
创建链表
void CreateList(LinkList &L,int n)
{
LinkList H,end;
L = (LinkList)malloc(sizeof(LNode));
if(L == NULL)exit(ERROR);
L->next = NULL;
end = L;
for(int i = n;i > 0;--i)
{
H = (LinkList)malloc(sizeof(LNode));
scanf(" %c",&H->data.word); //建立新结点
end->next = H;
end = H;
}
end->next = NULL;
}
链表逆置核心函数
LinkList ReverseList(LinkList &L)
{
LinkList p,q,m;
p = L->next;
if(p == NULL || p->next == NULL)
return L;
q = p->next;
m = q->next;
while(q!=NULL){
printf("1");
q->next = p;
p = q;
q = m;
if (m != NULL)m = m->next;
}
L->next->next = NULL;
L->next = p;
return L;
}
打印链表及主函数
void PrintList(LinkList L)
{
LinkList pa;
pa = L->next;
while(pa)
{
printf("%c ",pa->data.word);
pa = pa->next;
}
}
int main()
{
LinkList L;
ElemType e;
int n;
printf("输入字母个数“大写字母”:");
scanf("%d",&n);
CreateList(L,n);
PrintList(L);
//OK
printf("\n");
ReverseList(L);
PrintList(L);
//OK
return 0;
}
有帮到你可以打赏哦,0.01起步,上不封顶!!!