Reputation: 1
I need to move first symbol to the end by using lists. It should be moved to the end and deleted from the beggining. I am a begginer, so its is difficult to me. Thanks for help. Here is my code, I dont know what more shall I do...
#include <stdio.h>
#include <stdlib.h>
struct L
{
int symbol;
struct L *next;
};
typedef struct L List;
typedef List *ListPtr;
int main ()
{
int nr=0,i;
char a;
ListPtr lst ;
lst=(ListPtr) malloc(sizeof(List));
ListPtr start=lst;
printf("Enter list symbols (ctrl+z the end:\n");
scanf("%c",&(lst->symbol));
a=lst->symbol;
while (!feof(stdin))
{
lst->next=(ListPtr) malloc(sizeof(List));
lst=lst->next;
scanf("%c",&(lst->symbol));
nr++;
}
lst->next=(ListPtr) malloc(sizeof(List));
lst=lst->next;
lst->symbol=a;
lst->next=NULL;
lst=start;
printf("The list is:\n");
for (i=0; i<=nr; i++)
{
printf("%c",lst->symbol);
lst=lst->next;
}
printf("\n");
lst=start;
system("pause");
return 0;
}
Upvotes: 0
Views: 75
Reputation: 9648
Instead of copying the first symbol to the end, you can just update the pointers so the end of the list now points to the first element. We can do this in three steps:
Find the end of the list
Put the first element on the end
Point the head of the list to the new head.
ListPtr cur = lst;
if( !cur ) { // empty list }
while( cur->next ){ cur = cur->next; }
// 1. finished, end of list is cur
cur->next = lst;
// 2. finished, end of list is new element,
// but it is now a circular list as the last element still points to the first element
ListPtr new_head = lst->next;
lst->next = NULL;
lst = new_head;
Upvotes: 2