Что я пытаюсь сделать, это своп первого и последнего элементов отдельного списка. Пока у меня есть следующий код, где я создаю список и добавляю к нему некоторые номера. Моя проблема заключается в функции swapElements1.C - Сменить первый и последний элемент в одиночном списке
#include <stdio.h>
#include<stdlib.h>
struct node
{
int number;
struct node *next;
};
void addNodeSingle(struct node **head, int num, int thesi) //Function to insert new node at the beginning or the end of the list, depending on the value of "thesi"
{
if (*head == NULL)
{
struct node *current;
current = (struct node*) malloc (1*sizeof(struct node));
current -> number = num;
current -> next = NULL;
*head = current;
}
else
{
if (thesi == 0)
{
struct node *current;
current = (struct node*) malloc (1*sizeof(struct node));
current -> number = num;
current -> next = *head;
*head = current;
}
else
{
struct node *current, *temp;
current = (struct node*) malloc (1*sizeof(struct node));
current -> number = num;
temp = *head;
while (temp -> next != NULL)
temp = temp -> next;
temp -> next = current;
current -> next = NULL;
}
}
}
void displayList(struct node **head) //Function to display the list
{
struct node *current;
if(*head == NULL)
printf("I lista einai adeia!\n");
else
{
current= *head ;
while(current != NULL)
{
printf("%d ",current -> number);
current = current -> next;
}
}
}
void swapElements1(struct node **head) //(not working)Function to swap first and last element of the list
{
struct node *current, *temp;
current = temp = *head;
while(current != NULL)
{
temp = current;
current = current -> next;
}
*head = (*head)->next;
*head = temp;
current = NULL;
}
int main()
{
struct node *head;
head = NULL;
addNodeSingle(&head,5,1);
addNodeSingle(&head,6,1);
addNodeSingle(&head,2,0);
addNodeSingle(&head,7,0);
addNodeSingle(&head,8,0);
printf("List is: ");
displayList(&head);
swapElements1(&head);
printf("\nNew list is: ");
displayList(&head);
}
Выход я получаю:
Список является: 8 7 2 5 6
Новый список: 6
Что мне нужно, это:
Список является: 8 7 2 5 6
Новый список: 6 7 2 5 8
Вот demo
У вас есть четыре указателя для обновления: голова, следующий указатель в первом элементе, следующий указатель во втором-последнем элементе и следующий указатель в последнем элементе. – user3386109
Вы рассматривали прямое переключение данных вместо узлов? Или это школьное упражнение, которое это требует? –
@WeatherVane К сожалению, я хочу поменять местами, а не только данные. – user3120283