【问题标题】:Change address of pointer to linked list when sorting排序时更改指向链表的指针地址
【发布时间】: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


    【解决方案1】:

    Swap 函数关闭了 1。因此,在最里面的循环体中你需要Swap(tmp-&gt;prev, tmp) 而不是Swap(tmp, tmp-&gt;next)

    您需要比较和交换相同的元素,而不是比较当前和下一个元素,而是交换下一个和第二个下一个元素。 if( (tmp-&gt;data) &gt; (tmp-&gt;next-&gt;data) ),然后tmp-&gt;prev-&gt;next 应该指向tmp-&gt;nexttmp-&gt;next-&gt;next 应该指向tmp。 但是,需要注意一件事:当您 Swap(tmp-&gt;prev, tmp) 时,您还需要进一步启动一个元素。这一点从头部指向第一个元素但不包含任何数据这一事实也很清楚。 first-&gt;prev 应该指向头部,头部应该是 rw。

    可以让顶级代码保持头部,但如果 ll 代码保持自己的头部会更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 2017-12-13
      • 2020-12-30
      • 2013-07-12
      • 2021-09-06
      相关资源
      最近更新 更多