双向循环链表、正负数、输出
本帖最后由 奥普瓯江 于 2021-10-20 18:19 编辑原理:
注意:负数,补码转正数,
代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 26
typedef struct Like
{
char data;
struct Like *prior;
struct Like *next;
}Like, *Likes;
void InitList(Likes *E); //初始化双向链表并创建初始节点
void GetList(Likes *E); //创建26节点并向其中填入字母
void PutList(Like *E);
void PutList(Like *E)
{
Like *temp = E->next, *temps;
int i;
scanf("%d", &i);
getchar();
if(i > 0)
{
for(int j = 0; j < i; j++)
{
temp = temp->next;
}
temps = temp;
do
{
printf("%c", temp->data);
temp = temp->next;
}while(temp != temps);
}
else if(i < 0)
{
i = abs(i); //负数转正数
for(int j = 0; j <= i; j++)
{
temp = temp->prior;
}
temps = temp;
do
{
temp = temp->next;
printf("%c", temp->data);
}while(temp != temps);
}
//恢复指针
}
void GetList(Likes *E)
{
Like *temp, *tail;
for(int i = 0; i < MAXSIZE; i++)
{
temp = (Likes )malloc(sizeof(Like ));
temp->data = i + 65;
temp->next = (*E)->next;
(*E)->prior = temp;
(*E)->next->prior = temp;
if((*E)->next == *E)
{
(*E)->next = temp;
temp->prior = temp;
}
else
{
temp->prior = tail;
tail->next = temp;
}
tail = temp;
}
}
void InitList(Likes *E) //初始化双向链表并创建初始节点
{
if(*E != NULL)
{
Like *temp = (*E)->next, *temps;
do
{
temps = temp;
temp = temp->next;
free(temps);
}while(temp == NULL);
}
else
{
*E = (Likes )malloc(sizeof(Like ));
}
(*E)->next = *E;
(*E)->prior = *E;
}
int main()
{
Like *F = NULL;
InitList(&F);
GetList(&F);
PutList(F);
return 0;
}
页:
[1]