请问大家,尾插法怎么创建循环链表,这个代码的问题在哪?
本帖最后由 zxw09y 于 2020-2-14 10:53 编辑#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define OK 1
#define ERROR 0
#define Elemetype int
#define Status int
#define InitLen 5
typedef struct Linklist
{
Elemetype data;
struct Linklist *next;
}Linklist, *pLink;
Status ds_init(Linklist **head)
{
pLink cur, rear; //当前指针,尾指针
for(int i = 0; i < InitLen; i++)
{
if((*head) = NULL)/*循环链表中只有一个节点*/
{
(*head) = (pLink)malloc(sizeof(Linklist));
(*head)->data = rand()%100+1;
//(*head)->next = *head;
rear = (*head);
}
else
{
cur = (pLink)malloc(sizeof(Linklist));
if(!cur)
{
return ERROR;
}
cur->data = rand()%100+1;
rear->next = cur;
rear = cur;
}
}
rear->next = (*head);
return OK;
}
void Display(pLink head)
{
pLink p = head;
do
{
printf("%4d ",p->data);
}while((p = p->next) != head);
printf("\n");
}
int main(void)
{
pLink head = NULL;
int code;
srand((unsigned)time(NULL));
code = ds_init(&head);
printf("%d\n", code);
Display(head);
return 0;
} #define Elemetype int
#define Status int
这里应该有问题,是typedef才能取别名,define是定义参数(我也是新手嘿嘿,不晓得对不对) 唉,犯了个参见错误,if条件判断是时候变成赋值了,难怪出错
页:
[1]