单循环链表的遍历
【题目】:写一个对单循环链表进行遍历(打印每个结点的值)的算法,已知链表中任意结点的地址为p
typedef struct linknode
{
int data;
struct linknode *next;
}ListNode;
【输入形式】输入结点个数,再输入结点值
【输出形式】每个结点占一行
【样例输出】
5
5 4 3 2 1
【持续输出】
5
4
3
2
1
【代码实现】
#include <stdio.h>
#include<stdlib.h>
typedef struct linknode
{
int data;
struct linknode *next;
}ListNode;
ListNode *create();
void show(ListNode *p);
int main()
{
ListNode *p;
p=create();
show(p);
return 0;
}
ListNode *create()
{
ListNode *head,*p;
head=p=(ListNode *)malloc(sizeof(ListNode));
int i,n;
scanf("%d",&n);
for(i=0;i<n;i++)
{
p->next=(ListNode *)malloc(sizeof(ListNode));
scanf("%d",&p->next->data);
p=p->next;
}
p->next=head;
return head;
}
void show(ListNode *p)
{
ListNode *t;
t=p->next;
while(t!=p)
{
printf("%d\n",t->data);
t=t->next;
}
}
以上是实现效果