1

I'm trying to swap two pointers of a singly linked list using the bubble sort. I've made the compare function, and its working good. In the swap function, the swap is working good, I've managed to swap between the node and the node->next, though the linked list "lose" the info of the node (after the swap), so the first node in the linked list is node->next. I'm using a generic function which do the bubble sort and call the compare function and the swap function.

Any idea why this happens?

void swap_arr(void **arr,int i , int j)
{

  Team *teamList = (Team*) arr ;    
  Team *teamI = (Team*) arr , *teamJ ;
  Team *temp ;
  Team *temp1;
  int z;


  // Receives instead i
  for(z=0; z<i; z++)
    teamI = teamI->next;

  //teamJ is the i+1    
  teamJ =  teamI->next;

  temp = teamI;
  temp1 = teamJ->next;


  teamI = teamJ ;

  teamJ = temp;

  if (temp1->next->next==NULL)
     teamJ->next = NULL;
  else
     teamJ->next = temp1->next;

  teamI->next = teamJ;

   if (temp1==NULL)
     teamJ->next=NULL;
  else
     teamJ->next = temp1;  
}
4

2 回答 2

3

要交换两个节点 (a,b),您需要访问指向第一个的“外部”节点 (o)。(并且在 a 和 b 之后还有一个节点 p。(p 也可以为 NULL,但这并不重要)

老情况:

o->next == a
a->next == b
b->next == p

新情况:

o->next == b
b->next == a
a->next == p

仅当 o 实际上一个节点时才能执行此交换。(因此:有一个 o->next 指针),所以你需要特殊的代码来处理 a 是链头的情况。

但不是:o->next 只是一个“struct llist *”,因此可以使用任何指向 llist 的指针。在大多数情况下,最简单的解决方案是对交换函数使用指针到指针的参数;指向指针的指针既可以指向链的头部,也可以指向某个节点的 ->next 指针。

于 2012-01-24T10:02:27.120 回答
0

我还尝试使用冒泡排序来实现链表的排序,尽管您可以在代码中进行的修改不是编写交换函数,您可以只在代码中交换它们,每次您需要有 3 个不同的指针指向相邻节点。你可以在这里找到实现的代码。

于 2013-06-25T08:08:16.813 回答