链表-----交换任意两个元素

#include
#include 

//定义链表
typedef struct ListNode
{
	int data;
	struct ListNode *next;
}linklist;

linklist *head = NULL;

//创建链表
linklist*CreateList(int *arr, int len)
{
	linklist* p, *rear;
	head = (linklist*)malloc(sizeof(linklist));
	head->data = arr[0];
	rear = head;
	int count = 1;
	while (count < len-1)
	{
		p = (linklist*)malloc(sizeof(linklist));
		p->data = arr[count];
		rear->next = p;
		rear = p;
		count++;
	}
	rear->next = NULL;
	return head;
}
//找到p的前驱节点
linklist *FindPre(linklist *head, linklist *p)
{
	linklist *q = head;
	while (q)
	{
		if (q->next == p)
			return q;
		else
			q = q->next;
	}
	return NULL;
}
//交换链表任意两个元素
linklist *SwapTwoLink(linklist *head,linklist *p,linklist *q)
{
//当head或者p或者q为空时返回head;
	if (head == NULL || p == NULL || q == NULL)
		return head;
//当p,q相等时返回head;
	if (p->data == q->data)
		return head;
//当p->next ==q或者q->next ==p时是一种情况
	if (p->next == q)
	{
		linklist *pre_p = FindPre(head, p);
		pre_p->next = q;
		p->next = q->next;
		q->next = p;
	}
	else if (q->next == p)
	{
		linklist *pre_q = FindPre(head, q);
		pre_q->next = p;
		q->next = p->next;
		p->next = q;
	}
//当p!=q时又是另一种情况	
	else if (p != q)
	{
		linklist *pre_p = FindPre(head, p);
		linklist *pre_q = FindPre(head, q);
		linklist *after_p = p->next;
		p->next = q->next;
		q->next = after_p;
		pre_p->next = q;
		pre_q->next = p;
	}
//最后返回head
	return head;
}

//打印链表
void ShowList(linklist* p)
{
	printf("链表元素为:");
	while (p)
	{
		printf("%d ", p->data);
		p = p->next;
	}
	printf("\n");
}

//主函数
int main()
{
	int array[] = { 1,3,5,7,9,2,4,6,8,10 };
	CreateList(array, sizeof(array) / sizeof(array[0]));
	ShowList(head);
	linklist *p = head;
	linklist *q = head;
	while (p)
	{
		
		if (p->data == 5)
			break;
		p = p->next;
	}
	while (q)
	{
		
		if (q->data == 8)
			break;
		q = q->next;
	}
	linklist *SwapHead = SwapTwoLink(head,p,q);
	ShowList(SwapHead);
	

	return 0;
}

 

你可能感兴趣的:(链表-----交换任意两个元素)