【发布时间】:2021-02-13 14:42:34
【问题描述】:
这是我通过冒泡排序对链表进行排序的程序。当我使用 while 时没问题,但是当我使用 for 循环时,它有一个无限循环,所以我的程序意外停止。另一方面,对于第一个和第二个元素的第一次交换,我将指针头指向第二个,但它可能不适用于整个程序。
例如, 例1: 输入:3,2,4,1,5 输出:2,3,4,5
Ex2: 输入:4,3,2,1,5 输出:3,4,5
Ex3: 输入:3,2,1 输出:2,3
我认为它只是第一次改变了head指针指向的地址,所以head在Ex1中指向2,在Ex2中指向3,在Ex3中指向2。
void Swap(Node *p1, Node *p2)
{
Node *t;
t=p2->next;
p2->next=p1;
p1->next=t;
}
Node *BubbleSort(Node *head,int n) //pass the address of the first element in linked list and the linked list size
{
Node *tmp=head;
int swap=1;
for(int i=0;i<n-1;i++)
{
tmp=a; swap=0;
for(int j=0;j<n-1;j++)
{
if((tmp->data)>(tmp->next->data))
{
if(j==0) //if this is the first and second element I will change the address of the pointer
a=tmp->next;
Swap(tmp,tmp->next);
swap=1;
}
else tmp=tmp->next; //If the element I focus on is not greater than its folowing I will move the tmp pointer to the next.
}
if(swap==0)
return head;
}
return head;
}
int main()
{
Node*head;
//Assume I have a linked list with n elements
head=BubbleSort(head,n);
}
我在 GeekforGeek 中搜索了另一种方法,但我仍然想知道为什么我的代码不起作用。我想了差不多一天。请帮帮我!
【问题讨论】:
标签: c linked-list bubble-sort