69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
struct cyclink
{
char name[10];
int id;
struct cyclink *next;
};
struct cyclink *creat(struct cyclink **head)
{
struct cyclink *newnode;
struct cyclink *his;
*head = (struct cyclink *)malloc(sizeof(struct cyclink)); /*动态生成一个节点*/
*head = (*head)->next;
newnode = (struct cyclink *)malloc(sizeof(struct cyclink));
printf("first input num:");
scanf("%d", &newnode->id);
if (newnode->id != 0)
{
printf("first input name:");
scanf("%s", newnode->name);
*head = newnode->next;
}
while (newnode->id != 0)
{
if ((*head)->next == *head)
{
newnode = (*head)->next;
}
else
{
his->next = newnode;
}
his = newnode;
newnode = (struct cyclink *)malloc(sizeof(struct cyclink));
printf("more input num:");
scanf("%d", &newnode->id);
if (newnode->id != 0)
{
printf("more input name:");
scanf("%s", newnode->name);
*head = newnode->next;
}
}
return *head;
}
void print(struct cyclink *head)
{
struct cyclink *temp;
temp = head;
if (head == head->next)
{
printf("no node!\n");
}
else
{
while (temp != temp->next)
{
printf("id: %d\n", temp->id);
printf("name: %s\n", temp->name);
temp = temp->next;
}
}
}
int main()
{
struct cyclink *head;
head = creat(&head);
exit(0);
}
//如果已经搞定,just as reference.
#include <stdio.h>
#include <stdlib.h>
struct cyclink
{
char name[10];
int id;
struct cyclink *next;
};
struct cyclink *creat(struct cyclink **head)
{
struct cyclink *newnode;
struct cyclink *his;
*head = (struct cyclink *)malloc(sizeof(struct cyclink)); /*动态生成一个节点*/
//*head = (*head)->next;
newnode = (struct cyclink *)malloc(sizeof(struct cyclink));
printf("first input num:");
scanf("%d", &newnode->id);
getchar();
if (newnode->id != 0)
{
printf("first input name:");
scanf("%s", newnode->name);
//*head = newnode->next;
}
(*head)->next=newnode;//newnode为第一个节点.
his=newnode;//his ------尾指针
while (newnode->id != 0)
{
/* if ((*head)->next == *head)
{
newnode = (*head)->next;
}
else
{
his->next = newnode;
}
his = newnode;*/
newnode = (struct cyclink *)malloc(sizeof(struct cyclink));
printf("more input num:");
scanf("%d", &newnode->id);
getchar();
if (newnode->id != 0)
{
printf("more input name:");
scanf("%s", newnode->name);
//*head = newnode->next;
his->next=newnode;
his=newnode;//his 后移
}
}
free (newnode);//释放最后一个节点
his->next=*head;//与head相连,形成单循环链表
return *head;
}
void print(struct cyclink *head)
{
struct cyclink *temp;
temp = head->next;//head->next;
if (head == head->next)
{
printf("no node!\n");
}
else
{
while (temp->next != head)//head
{
printf("id: %d\n", temp->id);
printf("name: %s\n", temp->name);
temp = temp->next;
}
printf("id: %d\n", temp->id);
printf("name: %s\n", temp->name);
}
}
int main()
{
struct cyclink *head;
head = creat(&head);
print(head);
exit(0);
}