首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

循环单链表,该如何处理

2013-08-14 
循环单链表#include stdio.h#include string.h#include stdlib.hstruct node_t {int datastruct no

循环单链表

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct node_t {
int data;
struct node_t *next;
};
int main(void)
{
int num;
struct node_t head = {0, NULL};
struct node_t *new = NULL;
struct node_t *tail = NULL;

while(1)
{
printf("please input num:");
scanf("%d", &num);
if (num == -1)
break;

/*printf("num = %d\n", num);*/
new = (struct node_t *)malloc(sizeof(struct node_t));
if (new == NULL)
{
return -1;
}

new->data = num;
new->next = NULL;
for (tail = &head; tail->next != NULL; tail = tail->next)
continue;
tail->next = new;
}


for (tail = head.next; tail != NULL; tail = tail->next)
{
printf("%d ", tail->data);
}
printf("\n");

for (tail = head.next; tail != NULL; tail = new)
{
new = tail->next;
free(tail);
}
return 0;
}

如上,我要怎么改  能让他成为循环链表啊。。。晕死了。。。 单链表
[解决办法]
bug1-第一个元素插入时,未能构成循环队列:

head = new;                   
 head = new->next;

修改意见:

head=new;
new->next = head;


bug2插入操作错误

for(tail = head;  tail->next != head && new->data > tail->next->data; tail = tail->next)
tail->next = new;

修改意见:

for(tail = head;  tail->next != head && new->data > tail->next->data; tail = tail->next)//当条件不成立时,要么到结尾了tail->next==head.或者new->data <= tail->next->data;


//前者相当于直接插入到表尾,后者是插入当前tail后面
{
new->next = tail->next;
tail->next = new;
}

热点排行