将 linked 列表的头部与其中的 link 交换?

Swapping head of linked list with a link within it?

为了澄清标题:我像这样遍历 linked 列表 *head=(*head)->next 因为它是一个函数。在我的函数中,我选择 current headcurrent head 之间的另一个 link 和要交换的列表的末尾。

我想要的是创建一个函数来交换 head 和 link(不仅是数据),而且知道交换的所有条件都满足;这意味着 link 不是当前的 head 或者 link 不是 NULL。可以那样做还是我必须尝试其他方法?

提前致谢。

由于我的问题不清楚,所以我把问题给你。

我需要做一个这样的函数:

void intertwine(cvor **head)

我收到了一个 linked 随机数列表。我需要做的是交换 links 直到它看起来像这样:奇数,偶数,不均匀,偶数等

我必须尊重参差不齐的顺序。

如果偶数和不偶数的数量不相等,请按照它们在列表中的顺序排列。

这里有 2 个例子:

输入:11、7、5、16、12、15、17、13、10、4、1

输出:11、16、7、12、5、10、15、4、17、13、1

输入:1、3、2、4

输出:1、2、3、4

我当前的代码如下所示(未完成

edit2:抱歉忘记了语言障碍

typedef struct atom{
    int el;
    struct atom *next;
} cvor;

void intertwine (cvor **head){
    cvor *pom,int br=1;

    pom=*head;
    while(*head){
        if((*head)->el%2==(br%2)){
            pom=(*head)->next;
            while(pom){
                if(pom->el%2==(br+1)%2)break;
                pom=pom->next;
            }
            if(pom==NULL) return;

最后是我想要的交换发生的时间。

如果您编写一个函数可以将链表中的一个元素移动到同一链表中另一个元素的前面,则可以解决此问题。

作为输入函数应该采用

  • 指向head指针的指针'

  • 指向要移动的元素的指针b

  • 指向元素的指针 a,b 应移到

  • 前面

喜欢

void move_b_in_front_of_a(cvor **head, cvor* b, cvor* a) { ... }

调用函数时需要

  • ab都指向列表中的元素*head

  • a 在列表中位于 b 之前

实现可能是这样的:

void move_b_in_front_of_a(cvor **head, cvor* a, cvor* b)
{
  // Find the element just before a
  cvor* a_prev = find_element_before(head, a);

  // Find the element just before b (start from a)
  cvor* b_prev = find_element_before(a, b);
  if (b_prev == NULL) { .... add error handling ....}

  // Take b out of the list
  b_prev->next = b->next;

  // Insert b in front of a
  if (a_prev == NULL)
  {
    (*head) = b;
  }
  else
  {
    a_prev->next = b;
  }
  b->next = a;
}

在上面的代码中我使用了函数

cvor* find_element_before(cvor* l, cvor* e)
{
  // Add code to find the element just before e in the list l
  // Return NULL if e is first element
  // Add error handling if element e isn't found

  ...
  ...

  return pointer_to_element_just_before_e;
}

您需要实施。

有了这两个函数,实现intertwine函数应该就很容易了。

下面是一些可以帮助您入门的函数伪代码:

current_element = *head
expected-type = odd
loop:
    if current_element is expected-type
        toggle expected-type
        current_element = next
        if current_element is NULL return
    else
        find_element with_correct_type
        if no element found return
        move found_element in front of current_element  (use above function)
        current_element = found_element