#创建一个不带有头结点的循环单向链表(尾插法)
typedef struct Node{
int data;
struct Node* next;
}Node,*LNode;
LNode CreateListTail(int n){ //n为链表中节点的数目
LNode p,tail; //创建一个临时的中间指针变量p和一个尾指针tail;tail用于指向尾节点
LNode head=(LNode)malloc(sizeof(Node)); //创建一个头结点,head为指向头结点的指针
if(head==NULL)
return 0; //判断申请内存空间是否成功
head->next=NULL;
head->data=n; //head->data用来存储该链表中的节点数
tail=head; //尾节点先指向头结点,因为需要从尾部插入节点
for(int i=1;i<=n;i++){
p=(LNode)malloc(sizeof(Node)); //创建一个节点
p->data=i;
p->next=tail->next; //插入
tail->next=p; //节点p
tail=p; //并将尾指针向后移动
}
tail->next=head->next; //让tail->next和head->next同时指向第一个节点,这样就相当于把头结点从循环链表中剔除
return tail->next; //返回该链表中第一个节点
}
要点:
1.总共创建3个指针,head指向头结点,tail指向尾节点,p用于向链表中插入节点时指向新创建的节点
2.从尾部插入节点的语句:
p->next=tail->next;
tail->next=p;
tail=p;
3. tail->next和head->next要同时指向第一个节点
4.最后返回的是第一个节点,而不是头结点