Data structures: singly linked list reverse series 8--

Business need: Given a list head pointer pointing to a reversal list. Implementation process: Changing chain domain between adjacent nodes.

Example:

Input
l-> 2-> 3-> 4-> NULL
Output :
4-> 3-> 2-> l-> NULL

Input :
l-> 2-> 3-> 4-> 5-> NULL
Output :
5-> 4-> 3-> 2-> l-> NULL

Input : NULL
output : NULL

Input : 1-> NULL
Output : 1-> NULL

 

Iterative method:

Space complexity: O (1), time complexity: O (n)

1, the initialization 3 pointers

pre = NULL, curr = *head, next = NULL

2, iterate over the list, perform the following loop

// Before changing next of current,
// store next node
next = curr->next

// Now change next of current
// This is where actual reversing happens
curr->next = prev

// Move prev and curr one step forward
prev = curr
curr = next

The following is the algorithm implementation process:

// Iterative C program to reverse a linked list
#include <stdio.h>
#include <stdlib.h>

/* Link list node */
struct Node
{
    int data;
    struct Node* next;
};

/* function to reverse the linked list */
void reverse(struct Node** head_ref)
{
    struct Node* prev = NULL;
    struct Node* current = *head_ref;
    struct Node* next = NULL;

    while(current != NULL)
    {
        //Store next
        next = current->next;

        //Reverse current node's pointer
        current->next = prev;

        //Move pointers one position ahead.
        prev = current;
        current = next;
    }
    *head_ref = prev;
}

/* function to push a node */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}


/* function to print linked list */
void printList(struct Node* head)
{
    struct Node* temp = head;
    while(temp != NULL)
    {
        printf("%d ", temp->data);
        temp = temp->next;
    }
    printf("\n");
}

/* driver program to test above function */
int main() {

    /* Start with the empty list */
    struct Node* head = NULL;

    push(&head, 20);
    push(&head, 4);
    push(&head, 15);
    push(&head, 85);

    printf("Given linked list\n");
    printList(head);
    reverse(&head);
    printf("Reversed linked list\n");
    printList(head);

    return 0;
}

 

Source: https://www.geeksforgeeks.org/reverse-a-linked-list/

Guess you like

Origin www.cnblogs.com/passedbylove/p/11442956.html