不要着急。 :) 正如你所說,你需要交換節點本身,而不是交換隻是他們的價值觀,那麼你在這裏。 :)
#include <stdio.h>
#include <stdlib.h>
struct list
{
int value;
struct list *next;
};
void push_front(struct list **head, int value)
{
struct list *tmp = malloc(sizeof(struct list));
if (tmp)
{
tmp->value = value;
tmp->next = *head;
*head = tmp;
}
}
void display(struct list *head)
{
for (struct list *tmp = head; tmp; tmp = tmp->next)
{
printf("%d ", tmp->value);
}
printf("\n");
}
void swap(struct list **head, int value)
{
while (*head && (*head)->value != value)
{
head = &(*head)->next;
}
if (*head && (*head)->next)
{
struct list *next = (*head)->next->next;
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = next;
}
}
int main(void)
{
struct list *head = NULL;
push_front(&head, 4);
push_front(&head, -5);
push_front(&head, 3);
push_front(&head, 7);
push_front(&head, -1);
push_front(&head, 2);
display(head);
swap(&head, 2);
display(head);
swap(&head, 2);
display(head);
swap(&head, 2);
display(head);
swap(&head, 2);
display(head);
swap(&head, 2);
display(head);
swap(&head, 2);
display(head);
return 0;
}
程序輸出是
2 -1 7 3 -5 4
-1 2 7 3 -5 4
-1 7 2 3 -5 4
-1 7 3 2 -5 4
-1 7 3 -5 2 4
-1 7 3 -5 4 2
-1 7 3 -5 4 2
或者一個更有趣的例子
#include <stdio.h>
#include <stdlib.h>
struct list
{
int value;
struct list *next;
};
void push_front(struct list **head, int value)
{
struct list *tmp = malloc(sizeof(struct list));
if (tmp)
{
tmp->value = value;
tmp->next = *head;
*head = tmp;
}
}
void display(struct list *head)
{
for (struct list *tmp = head; tmp; tmp = tmp->next)
{
printf("%d ", tmp->value);
}
printf("\n");
}
void swap(struct list **head, int value)
{
while (*head && (*head)->value != value)
{
head = &(*head)->next;
}
if (*head && (*head)->next)
{
struct list *next = (*head)->next->next;
(*head)->next->next = *head;
*head = (*head)->next;
(*head)->next->next = next;
}
}
int main(void)
{
struct list *head = NULL;
int a[] = { 2, -1, 7, 3, -5, 4 };
for (size_t i = 0; i < sizeof(a)/sizeof(*a); i++)
{
push_front(&head, a[i]);
display(head);
for (size_t j = 0; j < i; j++)
{
swap(&head, a[i]);
display(head);
}
printf("\n");
}
display(head);
return 0;
}
程序輸出是
2
-1 2
2 -1
7 2 -1
2 7 -1
2 -1 7
3 2 -1 7
2 3 -1 7
2 -1 3 7
2 -1 7 3
-5 2 -1 7 3
2 -5 -1 7 3
2 -1 -5 7 3
2 -1 7 -5 3
2 -1 7 3 -5
4 2 -1 7 3 -5
2 4 -1 7 3 -5
2 -1 4 7 3 -5
2 -1 7 4 3 -5
2 -1 7 3 4 -5
2 -1 7 3 -5 4
2 -1 7 3 -5 4
像往常一樣,我的回答是最好的。:)
你到現在爲止寫了哪些在交換功能中不起作用的東西? – reshad
我在函數中使用了3個用head初始化的指針,然後花了一段時間找到所需值的節點。第一個指針位於具有值的節點之前的節點,具有值的節點之後的第三個指針以及第三個指針。 –
請使用編輯按鈕將其添加到您的原始問題。 – reshad