天天看點

C連結清單冒泡排序(交換節點排序)

廢話不多說,直接上排序函數吧

void sort_list(struct node* head)
{
	struct node* pre, * p, * q;
	struct node* tail = NULL;
	while (head->next != tail)//傳入的是帶頭節點的連結清單,為了簡便操作
	{						 //頭節點未指派,是以從head->next開始					
		pre = head;
		p = head->next;
		q = p->next;
		while (p->next != tail)
		{
			if (p->data > q->data)//升序排列
			{	//交換節點
				pre->next = q;
				p->next = q->next;
				q->next = p;
			}
			else
			{
				p = p->next;
			}
			q = p->next;//這裡,p,q如果交換了節點,p已經在if裡後移了
					   //不然p就在else裡後移,是以q指派p->next就行了
			pre = pre->next;
		}
		tail = p;//一次循環後,最後一個數已最大,tail前移
	}
}

           

其實上面的函數不使用q指針也可以,下面是函數的第二個while循環,也就第二個while循環有些不同,這也是我在網上看到的最常見的寫法了,上面的排序函數也是我依照它改動而來的。

while (p->next != tail)
		{
			if (p->data > p->next->data)
			{
				pre->next = p->next;
				p->next = pre->next->next;
				pre->next->next = p;
			}
			else
			{
				p = p->next;
			}
			pre = pre->next;
		}
           

下面是完整的代碼

#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct node)

struct node
{
	int data;
	struct node* next;
};

struct node* creat_list(void);
void sort_list(struct node* head);
void print_list(struct node* head);

struct node* creat_list(void)
{
	struct node* head = (struct node*)malloc(LEN);
	if (head)
	{
		head->next = NULL;
	}
	struct node* p1;
	struct node* p2 = head;
	printf("請輸入資料(輸入-1結束):");
	for (int i = 0;; i++)
	{
		p1 = (struct node*)malloc(LEN);
		if (p1)
		{
			scanf_s("%d", &p1->data);
			p1->next = NULL;
			if (p1->data == -1)
			{
				break;
			}
		}
		if (head && i == 0)
		{
			head->next = p1;
		}
		else if (p2)
		{
			p2->next = p1;
		}
		p2 = p1;
	}
	return head;
}

void sort_list(struct node* head)
{
	struct node* pre, * p, * q;
	struct node* tail = NULL;

	while (head->next != tail)
	{
		pre = head;
		p = head->next;
		q = p->next;
		while (p->next != tail)
		{
			if (p->data > q->data)//升序排列
			{	//交換節點
				pre->next = q;
				p->next = q->next;
				q->next = p;
				
				//pre->next = p->next;
				//p->next = pre->next->next;
				//pre->next->next = p;
			}
			else
			{
				p = p->next;
			}
			q = p->next;
			pre = pre->next;
		}
		tail = p;
	}
}

void print_list(struct node* head)
{
	struct node* p;
	for (p = head->next; p; p = p->next)
	{
		printf("%d ", p->data);
	}
}

int main(void)
{
	struct node* head;
	head = creat_list();
	if (head->next)
	{
		printf("輸入的資料:");
		print_list(head);
		putchar('\n');
		sort_list(head);
		printf("排序後的連結清單:");
		print_list(head);
	}
	else
	{
		printf("輸入為空");
	}
	return 0;
}
           

總的來說,emmm,沒啥可說的了,沒有了解的再好好捋捋吧。

繼續閱讀