0

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;
}
  • Could you please give an example of an input, the expected output and the actual output – Ingo Leonhardt Mar 18 '14 at 17:13
  • Please see [`while (!feof(file))` is always wrong](http://stackoverflow.com/questions/5431941/while-feof-file-is-always-wrong) for a discussion of why you do not write your input loop that way — C is not Pascal. – Jonathan Leffler Mar 18 '14 at 17:15
  • Also, using `scanf("%c",&(lst->symbol));` where `lst->symbol` is an `int`, not a `char`, is a recipe for unhappiness. You'll sort-of get away with it on little-endian machines as long as the high-order bytes of `lst->symbol` are zero; it will fail horribly on big-endian machines — basically because you're lying to `scanf()`. You say "assign to the `char *`" but actually pass it an `int *`. – Jonathan Leffler Mar 18 '14 at 17:18
  • I don't think you need to delete any element, just modify the adequate next pointer. Set the next pointer to NULL for the first element and set the next pointer of the last element to point to the first element instead of null. Inserting/deleting elements in a linked list is just changing pointers and freeing memory if need be. – OAnt Mar 18 '14 at 17:22

1 Answers1

2

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:

  1. Find the end of the list

  2. Put the first element on the end

  3. 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;
clcto
  • 9,530
  • 20
  • 42