我一直在尝试交换链表中的元素。交换需要用开头的第三个元素和结尾的第三个元素来完成。我已经尝试实现一个 Double Linked List 并尝试从最后一个节点迭代以从最后一个节点找到第三个位置。 我想出了以下解决方案: - 从列表的开头找到第三个元素。 -减去(长度-位置)并找到下一个元素。我不知道我哪里错了,我已经查找了几个不同的解决方案,但无法弄清楚为什么它不起作用。
#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
int data;
struct Node *next;
} Node;
Node *head = NULL;
void insert();
void display();
void swap();
int main()
{
int choice;
while (1)
{
printf("\n1.Insert beggining\n");
printf("2.Display\n");
printf("3.Swap\n");
scanf("%d", &choice);
switch (choice)
{
case 1:
{
insert();
break;
}
case 2:
{
display();
break;
}
case 3:
{
swap();
break;
}
default:
{
printf("Error!\n");
return 0;
}
}
}
return 0;
}
void insert()
{
Node *current;
current = (Node *) malloc(sizeof(Node));
if (current == NULL)
{
printf("Out of memory!\n");
return;
}
printf("Enter a value \n");
scanf("%d", ¤t -> data);
current -> next = NULL;
if (head == NULL)
{
head = current;
}
else
{
current -> next = head;
head = current;
}
}
void display()
{
Node *temp;
if (head == NULL)
{
printf("List is empty!\n");
return;
}
else
{
temp = head;
while (temp != NULL)
{
printf("%d ", temp->data);
temp = temp -> next;
}
}
}
void swap()
{
Node *current1, *current2, *prev1, *prev2, *temp;
temp = NULL;
int k;
int n;
printf("Enter a range: \n");
scanf("%d", &n);
printf("Enter a pos: \n");
scanf("%d", &k);
prev1 = NULL;
prev2 = NULL;
current1 = head;
for (int i = 0; i < n; ++i)
{
current1 = current1 -> next;
if (i == k)
{
prev1 = current1;
}
}
current2 = head;
for (int i = 0; i<n-k-1; ++i)
{
prev2 = current2;
current2 = current2 -> next;
}
prev1 -> next = current2;
prev2 -> next = current1;
temp = current1 -> next;
current1 -> next = current2 -> next;
current2 -> next = temp;
}
注意:k - 是需要交换的元素的位置(开始位置相同,结束位置相同); N - 是从索引 0 开始的列表的长度 编辑:我已经包含了主要功能,列表功能的显示并在开头插入了一个元素。
示例输入:
10 3
1 2 3 4 5 6 7 8 9 10
样本输出:
1 2 3 7 5 6 4 8 9 10