不要着急。 :) 正如你所说,你需要交换节点本身,而不是交换只是他们的价值观,那么你在这里。 :)
#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