Search code examples
cpointerslinked-listsentinel

Linked list with sentinel


There is a linked list with sentinel at each end of the list S(sentinel)->1->2->3->4->5->6->S (something like this). I have to swap the neighbor elements: S->1->2->3->4->5->S to S->2->1->4->3->5->S but the code does this instead:2->1->4->3->-842150451. this code should work for every kind of input: S->1->2->S, S->1->S, etc. I have to make a new list connection in the original code. Changing the value of the integer in the nodes is forbidden. I believe that my void reverse_pairs(list* head) function is bad, but I don't now how to make it work.

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

typedef struct _list {
    int a;
    struct _list* next;
}list;
    

void reverse_pairs(list* head)
{
    if (head)
    {
        for (; head->next && head->next->next; head = head->next->next)
        {
            list* tmp = head->next;
            head->next = head->next->next;

            tmp->next = head->next->next;
            head->next->next = tmp;
        }
    }
}


list* makesentinel() 
{
    list* stra1 = (list *)malloc(1 * sizeof(list));
    list* stra2 = (list*)malloc(1 * sizeof(list));
    stra1->next = stra2;
    stra2->next = NULL;
    return stra1;
}
void push(list* head_ref, int new_data)
{
    list* new_list = (list*)malloc(sizeof(list));
    new_list->a = new_data;
    new_list->next = head_ref->next;
    head_ref->next = new_list;
}
void print(struct _list* node)
{
    list* temp = NULL;
    temp = node->next;
    while (temp->next != NULL) {
        printf("%d ", temp->a);
        temp = temp->next;
    }
}

int main()
{
    list* start = NULL;
    start = makesentinel();
    push(start, 5);
    push(start, 4);
    push(start, 3);
     push(start, 2);
     push(start, 1);

    printf("before\n");
    print(start);

    reverse_pairs(start);

    printf("\nafter\n");
    print(start);

    return 0;
}

Solution

  • Your problem is that you never test whether the last pair is complete. If your linked list contains an even number of elements, your code works fine (just try to add push(start, 6);).

    So you have to test one step further in reverse_pairs:

    void reverse_pairs(list* head)
    {
        if (head)
        {
            for (; head->next && head->next->next && head->next->next->next; head = head->next->next)
            {
                ...