C-单链接列表中的两个节点交换两个节点



我在单个链接列表中遇到了麻烦。我的代码当前在列表的开始时都可以正常工作。

编辑:我正在学习有关ADT的知识,因此我无法更改功能输入和输出。

typedef struct textbuffer *TB;
struct textbuffer {
    char *data;
    TB next;
};
void swapTB(TB tb, int pos1, int pos2) {
    if (tb == NULL || pos1 == pos2) return;
    int totalLines = linesTB(tb) - 1;
    if (pos1 < FIRST_LINE || pos1 > totalLines || pos2 < FIRST_LINE || pos2 > totalLines) {
        printf("Error: line number out of range, %d-%d.n", FIRST_LINE, totalLines);
        abort();
    } else {
        TB all = tb;
        int i = 0;
        TB prevX = NULL;
        TB currX = tb;
        while (i != pos1) {
            prevX = currX;
            currX = currX->next;
            i++;
        }
        int j = 0;
        TB prevY = NULL;
        TB currY = tb;
        while (j != pos2) {
            prevY = currY;
            currY = currY->next;
            j++;
        }
        if (prevX != NULL) {
            prevX->next = currY;
        } else {
            all = currY; //update head of list
        }
        if (prevY != NULL) {
            prevY->next = currX;
        } else {
            all = currX; //update head of list
        }
        TB temp = currY->next;
        currY->next = currX->next;
        currX->next = temp;
    }
    //return all;
}

我知道我的交换节点的方式是正确的,因为如果我更改功能以返回结核病(在这种情况下,全部),则可以正常工作。

我的问题是如何使用void函数来完成操作,而不更改功能所采用的内容?我想我需要头指针吗?但是我该如何使用?

做两件事: - 通过函数中的struct textbuffer的地址传递。

void swaptb(tb *tb,int pos1,int pos2)

在main()中: -

swaptb(tb,pos1,pos2);

,还要检查您的Currx和Curry null是否为null。

typedef struct node *TB;
struct node
{
    int data;
    TB next;
};
TB head=NULL;
void swapNodes(TB head_ref, int x, int y)
{
   if (x == y) return;
  head = head_ref;
   struct node *prevX = NULL, *currX = head_ref;
   while (currX && currX->data != x)
   {
       prevX = currX;
       currX = currX->next;
   }
   struct node *prevY = NULL, *currY = head_ref;
   while (currY && currY->data != y)
   {
       prevY = currY;
       currY = currY->next;
   }
   if (currX == NULL || currY == NULL)
       return;
   if (prevX != NULL)
       prevX->next = currY;
   else
       head = currY;
   if (prevY != NULL)
       prevY->next = currX;
   else
       head = currX;
   struct node *temp = currY->next;
   currY->next = currX->next;
   currX->next  = temp;
}
int main()
{
    TB start=NULL;
    // Create linked list here
    swapNodes(start, pos1, pos2);
    print_linkedlist(head);  // print the linked list after swap
    return 0;
}

最新更新