Create a circular singly linked list without leading nodes, insert nodes from the tail

#Create a circular singly linked list without a head node (tail interpolation)

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;				//返回该链表中第一个节点
}

Key points:
1. Create a total of 3 pointers, head points to the head node, tail points to the tail node, and p is used to point to the newly created node when inserting a node into the linked list.
2. A statement to insert a node from the tail:
p->next=tail ->next;
tail->next=p;
tail=p;
3. tail->next and head->next should point to the first node at the same time
4. Finally, the first node is returned, not the head node

Guess you like

Origin blog.csdn.net/qq_45465526/article/details/101558265