For starters according to the C Standard the function main
without parameters shall be declared like
int main( void )
In this loop
for(i=0;i<6;i++){
list->data=i;
list->next = (struct Node *)malloc(sizeof(struct Node));
list = list->next;
}
list->next = NULL;
there is allocated a redundant node with an inderterminate value of the data member data
.
The condition in this while loop
while(list->next->next!=NULL){
int temp = list->data;
list->data = list->next->data;
list->next->data = temp;
list = list->next->next;
}
is wrong and leads to undefined behavior due to this statement at the end of the loop
list = list->next->next;
The condition should be written like
while ( list && list->next )
Using your approach the program can look the following way
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
int main(void)
{
struct Node *list, *head;
const int N = 6;
head = ( struct Node * )malloc( sizeof( struct Node ) );
list = head;
int i = 0;
do
{
list->data = i;
} while ( ++i < N && ( list = list->next = ( struct Node *)malloc( sizeof( struct Node ) ) ) );
list->next = NULL;
printf("Original list: ");
for ( list = head; list; list = list->next )
{
printf( "%d ", list->data );
}
putchar( '\n' );
list = head;
while ( list && list->next )
{
int temp = list->data;
list->data = list->next->data;
list->next->data = temp;
list = list->next->next;
}
printf("Pair swapped list: ");
for ( list = head; list; list = list->next )
{
printf( "%d ", list->data );
}
putchar( '\n' );
return 0;
}
Its output is
Original list: 0 1 2 3 4 5
Pair swapped list: 1 0 3 2 5 4
You can add yourself checks that malloc(s) were successfull.
A more safe program can be written using the variable list
of the type struct Node **
.
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
int main(void)
{
const int N = 6;
struct Node *head;
struct Node **list;
list = &head;
for ( int i = 0; ( i < N ) && ( *list = ( struct Node *)malloc( sizeof( struct Node ) ) ); i++ )
{
if ( *list )
{
( *list )->data = i;
list = &( *list )->next;
}
}
*list = NULL;
printf("Original list: ");
for ( list = &head; *list; list = &( *list )->next )
{
printf( "%d ", ( *list )->data );
}
putchar( '\n' );
list = &head;
while ( *list && ( *list )->next )
{
int temp = ( *list )->data;
( *list )->data = ( *list )->next->data;
( *list )->next->data = temp;
list = &( *list )->next->next;
}
printf("Pair swapped list: ");
for ( list = &head; *list; list = &( *list )->next )
{
printf( "%d ", ( *list )->data );
}
putchar( '\n' );
return 0;
}
Take into account that you should free all allocated memory for the list.
And one more remark. The program does not swap nodes. It swaps values of the data member data
of adjacent nodes.:)