循环链表:
最后节点的next指针不指向NULL,直接改为指向首节点就行。(循环列表不需要头节点)。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
typedef struct student
{
int num;
struct student *next;
}Lstudent,*LPstudent;
void InitLink(LPstudent *phead)
{
Lstudent *ptr,*r;
*phead=NULL;
int n;
printf("please input number of student:\n");
scanf("%d",&n);
while(n>0)
{
ptr=malloc(sizeof(Lstudent));
ptr->num=n;
ptr->next=NULL;
if(*phead==NULL)
*phead=ptr;
else
r->next=ptr;
r=ptr;
printf("please input number of student:\n");
scanf("%d",&n);
}
ptr->next=*phead;//使末尾的next指针指向首节点
}
void printf_link(Lstudent *ptri)
{
while(ptri!=NULL)
{
printf("%d\n",ptri->num);
ptri=ptri->next;sleep(1);//加一个sleep函数便于输出
}
}
int main()
{
LPstudent head;
InitLink(&head);
printf_link(head);
}
双向链表:
需要加一个指向前一个节点的指针。
#include<stdio.h>
#include<stdlib.h>
typedef struct student
{
int num;
struct student *next;
struct student *prior;
}LDstudent,*LDPstudent;
void InitLink(LDPstudent *phead)
{
*phead=NULL;
LDPstudent ptr;
LDPstudent r=ptr;//后插入需要加一个指针
int n;
printf("please input num of student:\n");
scanf("%d",&n);
while(n>0)
{
ptr=malloc(sizeof(LDstudent));
ptr->num=n;
/* ptr->next=*phead;//前插入的方式
ptr->prior=NULL;
if(*phead!=NULL)
(*phead)->prior=ptr;
*phead=ptr;
*/
//后插入
ptr->next=NULL;
if(*phead==NULL)
{ ptr->prior=NULL;
*phead=ptr;}
else
{ ptr->prior=r;
r->next=ptr;}
r=ptr;
printf("please input num of student:\n");
scanf("%d",&n);
}
}
void printf_link(LDstudent *ptr)
{
LDPstudent p1=ptr;
printf("正序打印:\n");
while(p1!=NULL)
{
printf("%d\t",p1->num);
p1=p1->next;
}
printf("\n");
printf("反序打印:\n");
p1=ptr;
while(p1->next!=NULL)
p1=p1->next;
while(p1!=NULL)
{
printf("%d\t",p1->num);
p1=p1->prior;
}
}
int main()
{
LDPstudent head;
InitLink(&head);
printf_link(head);
}