單鏈表的操作

數據結構:

typedef int DataType;
typedef struct Node
{
	DataType data;
	struct Node *next;
}Node,* LinkList;

1、從尾到頭打印單鏈表

void TailToFrontPrint(LinkList head)
/*從尾到頭打印單鏈表*/
{
	if (head != NULL)
	{
		TailToFrontPrint(head->next);
		printf("%d ", head->data);
	}
}

2、刪除一個無頭單鏈表的非尾結點

void DelNoneTailNode(Node *pos)
/*刪除一個無頭單鏈表的非尾結點*/
{
	assert(pos);
	if (pos->next == NULL)
	{
		return;
	}
	Node *del = pos->next;
	pos->data = del->data;
	pos->next = del->next;
	free(del);
	del = NULL;
}

3、在無頭單鏈表的一個非頭結點前插入一個結點

void InsNoneFrontNode(Node *pos,DataType x)
/*在無頭單鏈表的一個非頭結點前插入一個結點*/
{
	Node *s = (Node *)malloc(sizeof(Node));
	s->data = pos->data;
	pos->data = x;
	s->next = pos->next;
	pos->next = s;
}

4、逆置/反轉單鏈表

void ReverseNode(LinkList &head)
/*反轉單鏈表*/
{
	Node *front = NULL;
	Node *tmp = head;
	Node *start = NULL;
	while (tmp != NULL)
	{
		start = tmp->next;
		tmp->next = front;
		front = tmp;
		tmp = start;
	}
	head = front;
}

5、查找單鏈表的中間節點,要求只遍歷一次鏈表

Node * FindMidNode(LinkList head)
/*查找單鏈表的中間結點*/
{
Node *slow = head;
Node *fast = head;
while (fast && fast->next)
{
fast = fast->next->next;
if (fast == NULL)
/*有if偶數時返回較小,無if返回較大*/
{
break;
}
slow = slow->next;
}
return slow;
}

6、查找單鏈表的倒數第k個結點,要求只遍歷一次鏈表

Node * FindKNode(LinkList head, int k)
/*返回倒數第k個結點*/
{
	assert(head);
	/*1、k大於head的長度
	2、*/
	Node *slow = head;
	Node *fast = head;
	while (k--)
	{
		if (fast == NULL)
		{
			return NULL;
		}
		else
		{
			fast = fast->next;
		}
	}
	while (fast)
	{
		slow = slow->next;
		fast = fast->next;
	}
	return slow;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章