C語言:循環單鏈表的創建,遍歷,插入


/*
	1.循環單鏈表的創建,由尾節點指向該鏈表,
	2.循環鏈表遍歷
	3.求鏈表的長度
	4.向鏈表中插入元素
*/

# include <stdio.h>
# include <malloc.h>


typedef struct node
{
	int data;
	struct node * pNext;
}NODE, * PNODE;


PNODE creat_list();    //創建鏈表
void travese(PNODE T);   //遍歷鏈表
void insert(PNODE &T, int pos, int val);  //插入元素
int length(PNODE T);  //求鏈表的長度

int main(void)
{
	//返回循環鏈表的尾指針
	PNODE T = creat_list();
	travese(T);

	//若在第一個有效節點前插入新節點5
	insert(T, 4, 5);
	travese(T);

	return 0;
}

//循環單鏈表的創建,返回尾節點
PNODE creat_list()
{
	PNODE pHead = (PNODE)malloc(sizeof(NODE));  //頭結點
	pHead->pNext = pHead;

	PNODE pTail = pHead; //尾指針
	PNODE pNew;

	int len;
	int i;
	int val;

	printf("輸入此循環鏈表的長度 len = ");
	scanf("%d", &len);

	for(i = 0; i < len; i++)
	{
		printf("輸入第%d個元素的值 val = ", i+1);
		scanf("%d", &val);

		pNew = (PNODE)malloc(sizeof(NODE));  //開辟新節點

		pNew->data = val;
		pNew->pNext = pHead;  //新節點的指針域始終指向頭結點

		pTail->pNext = pNew;
		pTail = pNew;
	}

	return pTail;  //返回尾指針
}

//循環單鏈表的遍歷
void travese(PNODE T)
{
	PNODE pHead = T->pNext;   //pHead指向頭結點
	PNODE p = pHead->pNext;   //p指向首節點,第一個有效節點

	while(p != pHead)  //循環鏈表的終止條件:(p != 頭指針)
	{
		printf("%d ", p->data);
		p = p->pNext;
	}
	printf("\n");
}

//向第pos個有效節點前,插入新節點
void insert(PNODE &T, int pos, int val)  //可能會改變尾指針的位置
{
	PNODE pHead = T->pNext; //pHead指向頭結點

	PNODE pNew = (PNODE)malloc(sizeof(NODE));
	pNew->data = val;

	PNODE p = pHead->pNext;  //指向第一個有效節點
	
	int len = length(T);
	int count = 0;

	if(1 == pos)  //插入到第一個有效節點前
	{
		pNew->pNext = pHead->pNext;

		pHead->pNext = pNew;
	}
	if(pos >1 && pos < len + 1)
	{
		while(p != NULL)
		{
			count ++;
			if(count == pos -1)  //pos位置前一個節點
			{
				pNew->pNext = p->pNext;
				p->pNext = pNew;
				break;			
			}
			p = p->pNext;
		}
		
	}
	if(pos == len + 1)  //在鏈表尾插入一節點
	{	
		pNew->pNext = T->pNext;
		T->pNext = pNew;
		T = pNew;
	}
	if(pos > len + 1)
	{
		printf("插入位置錯誤!");
		return;
	}

}

//求鏈表的長度
int length(PNODE T)
{
	PNODE pHead = T->pNext;
	PNODE p = pHead->pNext;

	int len = 0;

	while(p != pHead)
	{
		len ++;
		p = p->pNext;
	}
	return len;
}


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2021 ITdaan.com