[英]How to swap two adjacent items in a doubly linked-list in C
我正在編寫一個程序,在該程序中,我需要僅使用指針而不交換數據來交換雙向鏈表中的兩個相鄰節點,但它不起作用。
我被困了一段時間。 我試圖復制在互聯網上找到的一些解決方案,但似乎沒有任何效果。 這是 incriminated 函數(其中 b 是 a->next):
t_chstat *swap_node(t_chstat **a, t_chstat **b)
{
(*a)->next = (*b)->next;
(*b)->prev = (*a)->prev;
(*a)->prev = (*b);
(*b)->next = (*a);
if ((*b)->prev != NULL)
(*b)->prev->next = (*b);
if ((*a)->next != NULL)
(*a)->next->prev = (*a);
return (*b);
}
當我嘗試將 printfs 放在每一行以嘗試查看可能是什么問題時,我意識到第一條指令更改了 (*b) 的值並使其成為 (*b)->next,即使我覺得它應該只更改 (*a) 節點中包含的地址。 我不知道它為什么會這樣做以及如何解決它。
下面是 t_chstat 的定義:
typedef struct s_chstat
{
char *path;
struct s_chstat *next;
struct s_chstat *prev;
} t_chstat;
未測試(可能我遺漏了什么
typedef struct str_t
{
struct str_t *prev;
struct str_t *next;
}str_t;
void swap(str_t *a, str_t *b)
{
str_t *saved_prev = a -> prev;
str_t *saved_next = a -> next;
a -> next = b -> next;
a -> prev = b -> prev;
if(b -> next) (b -> next) -> prev = a;
if(b -> prev) (b -> prev) -> next = a;
if(saved_prev) saved_prev -> next = b;
if(saved_next) saved_next -> prev = b;
b -> prev = saved_prev;
b -> next = saved_next;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.