【发布时间】:2017-05-05 09:27:18
【问题描述】:
我在交换单链表中的节点时遇到问题。当两个节点都不是列表的开头时,我的代码当前有效。
编辑:我正在学习 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;
}
我知道我交换节点的方式是正确的,因为如果我更改为返回 TB(在本例中为全部)的函数,那么它就可以工作。
我的问题是如何使用 void 函数而不改变函数接收的内容?我想我需要一个头指针?但是我该如何使用呢?
【问题讨论】:
-
这段代码看起来非常复杂。顺便说一句,请提供minimal reproducible example。
-
TB是隐藏指针吗?否则,它的可见性/范围仅限于swapTB函数。 -
将这些信息添加到您的帖子中。
-
我选择使用单链表所以我这样写了struct,不知道要不要在里面加个TB头?
-
头节点必须传递给该函数。我没有得到这个问题。
标签: c function pointers linked-list