Mover el primer elemento al final de una Lista Vinculada dada

Escriba una función en C que mueva el primer elemento hasta el final en una lista enlazada individual dada. Por ejemplo, si la lista enlazada dada es 1->2->3->4->5, entonces la función debería cambiar la lista a 2->3->4->5->1.

Algoritmo: 

Recorra la lista hasta el último Node. Use dos punteros: uno para almacenar la dirección del último Node (último) y otro para la dirección del primer Node (primero). Después del final del ciclo, realice las siguientes operaciones. 
i) Hacer head como segundo Node (*head_ref = first->next). 
ii) Establecer el siguiente del primero como NULL (primero->siguiente = NULL). 
iii) Establecer el penúltimo como primero (último->siguiente = primero) 

C++

/* C++ Program to move first element to end
   in a given linked list */
#include <stdio.h>
#include <stdlib.h>
 
/* A linked list node */
struct Node {
    int data;
    struct Node* next;
};
 
/* We are using a double pointer head_ref
   here because we change head of the linked
   list inside this function.*/
void moveToEnd(struct Node** head_ref)
{
    /* If linked list is empty, or it contains
       only one node, then nothing needs to be
       done, simply return */
    if (*head_ref == NULL || (*head_ref)->next == NULL)
        return;
 
    /* Initialize first and last pointers */
    struct Node* first = *head_ref;
    struct Node* last = *head_ref;
 
    /*After this loop last contains address
    of last node in Linked List */
    while (last->next != NULL) {
        last = last->next;
    }
 
    /* Change the head pointer to point
       to second node now */
    *head_ref = first->next;
 
    /* Set the next of first as NULL */
    first->next = NULL;
 
    /* Set the next of last as first */
    last->next = first;
}
 
/* UTILITY FUNCTIONS */
/* Function to add a node at the beginning
   of Linked List */
void push(struct Node** head_ref, int new_data)
{
    struct Node* new_node = new Node;
    new_node->data = new_data;
    new_node->next = (*head_ref);
    (*head_ref) = new_node;
}
 
/* Function to print nodes in a given linked list */
void printList(struct Node* node)
{
    while (node != NULL) {
        printf("%d ", node->data);
        node = node->next;
    }
}
 
/* Driver program to test above function */
int main()
{
    struct Node* start = NULL;
 
    /* The constructed linked list is:
     1->2->3->4->5 */
    push(&start, 5);
    push(&start, 4);
    push(&start, 3);
    push(&start, 2);
    push(&start, 1);
 
    printf("\n Linked list before moving first to end\n");
    printList(start);
 
    moveToEnd(&start);
 
    printf("\n Linked list after moving first to end\n");
    printList(start);
 
    return 0;
}

Java

/* Java Program to move first element to end
in a given linked list */
class Sol
{
     
/* A linked list node */
static class Node
{
    int data;
    Node next;
};
 
/* We are using a double pointer head_ref
here because we change head of the linked
list inside this function.*/
static Node moveToEnd( Node head_ref)
{
    /* If linked list is empty, or it contains
    only one node, then nothing needs to be
    done, simply return */
    if (head_ref == null || (head_ref).next == null)
        return null;
 
    /* Initialize first and last pointers */
    Node first = head_ref;
    Node last = head_ref;
 
    /*After this loop last contains address
    of last node in Linked List */
    while (last.next != null)
    {
        last = last.next;
    }
 
    /* Change the head pointer to point
    to second node now */
    head_ref = first.next;
 
    /* Set the next of first as null */
    first.next = null;
 
    /* Set the next of last as first */
    last.next = first;
    return head_ref;
}
 
/* UTILITY FUNCTIONS */
/* Function to add a node at the beginning
of Linked List */
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
/* Function to print nodes in a given linked list */
static void printList( Node node)
{
    while (node != null)
    {
        System.out.printf("%d ", node.data);
        node = node.next;
    }
}
 
/* Driver code */
public static void main(String args[])
{
    Node start = null;
 
    /* The constructed linked list is:
    1.2.3.4.5 */
    start = push(start, 5);
    start = push(start, 4);
    start = push(start, 3);
    start = push(start, 2);
    start = push(start, 1);
 
    System.out.printf("\n Linked list before moving first to end\n");
    printList(start);
 
    start = moveToEnd(start);
 
    System.out.printf("\n Linked list after moving first to end\n");
    printList(start);
}
}
 
// This code is contributed by Arnab Kundu

Python3

# Python3 Program to move first element to end
# in a given linked list
 
# A linked list node
class Node:
    def __init__(self):
        self.data = 0
        self.next = None
 
# We are using a double pointer head_ref
# here because we change head of the linked
# list inside this function.
def moveToEnd( head_ref) :
 
    # If linked list is empty, or it contains
    # only one node, then nothing needs to be
    # done, simply return
    if (head_ref == None or (head_ref).next == None) :
        return None
 
    # Initialize first and last pointers
    first = head_ref
    last = head_ref
 
    # After this loop last contains address
    # of last node in Linked List
    while (last.next != None) :
     
        last = last.next
     
    # Change the head pointer to point
    # to second node now
    head_ref = first.next
 
    # Set the next of first as None
    first.next = None
 
    # Set the next of last as first
    last.next = first
    return head_ref
 
# UTILITY FUNCTIONS
# Function to add a node at the beginning
# of Linked List
def push( head_ref, new_data) :
 
    new_node = Node()
    new_node.data = new_data
    new_node.next = (head_ref)
    (head_ref) = new_node
    return head_ref
 
# Function to print nodes in a given linked list
def printList(node) :
 
    while (node != None):
     
        print(node.data, end = " ")
        node = node.next
     
# Driver code
 
start = None
 
# The constructed linked list is:
#1.2.3.4.5
start = push(start, 5)
start = push(start, 4)
start = push(start, 3)
start = push(start, 2)
start = push(start, 1)
 
print("\n Linked list before moving first to end")
printList(start)
 
start = moveToEnd(start)
 
print("\n Linked list after moving first to end")
printList(start)
 
# This code is contributed by Arnab Kundu

C#

/* C# Program to move first element to end
in a given linked list */
using System;
 
class GFG
{
     
/* A linked list node */
public class Node
{
    public int data;
    public Node next;
};
 
/* We are using a double pointer head_ref
here because we change head of the linked
list inside this function.*/
static Node moveToEnd( Node head_ref)
{
    /* If linked list is empty, or it contains
    only one node, then nothing needs to be
    done, simply return */
    if (head_ref == null || (head_ref).next == null)
        return null;
 
    /* Initialize first and last pointers */
    Node first = head_ref;
    Node last = head_ref;
 
    /*After this loop last contains address
    of last node in Linked List */
    while (last.next != null)
    {
        last = last.next;
    }
 
    /* Change the head pointer to point
    to second node now */
    head_ref = first.next;
 
    /* Set the next of first as null */
    first.next = null;
 
    /* Set the next of last as first */
    last.next = first;
    return head_ref;
}
 
/* UTILITY FUNCTIONS */
/* Function to add a node at the beginning
of Linked List */
static Node push( Node head_ref, int new_data)
{
    Node new_node = new Node();
    new_node.data = new_data;
    new_node.next = (head_ref);
    (head_ref) = new_node;
    return head_ref;
}
 
/* Function to print nodes in a given linked list */
static void printList( Node node)
{
    while (node != null)
    {
        Console.Write("{0} ", node.data);
        node = node.next;
    }
}
 
/* Driver code */
public static void Main(String []args)
{
    Node start = null;
 
    /* The constructed linked list is:
    1.2.3.4.5 */
    start = push(start, 5);
    start = push(start, 4);
    start = push(start, 3);
    start = push(start, 2);
    start = push(start, 1);
 
    Console.Write("\n Linked list before moving first to end\n");
    printList(start);
 
    start = moveToEnd(start);
 
    Console.Write("\n Linked list after moving first to end\n");
    printList(start);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// JavaScript program to move first element
// to end in a given linked list
 
/* A linked list node */
class Node
{
    constructor()
    {
        this.data = 0;
        this.next = null;
    }
}
 
/* We are using a double pointer head_ref
here because we change head of the linked
list inside this function.*/
function moveToEnd(head_ref)
{
     
    /* If linked list is empty, or it contains
    only one node, then nothing needs to be
    done, simply return */
    if (head_ref == null || head_ref.next == null)
        return null;
     
    /* Initialize first and last pointers */
    var first = head_ref;
    var last = head_ref;
     
    /*After this loop last contains address
    of last node in Linked List */
    while (last.next != null)
    {
        last = last.next;
    }
     
    /* Change the head pointer to point
    to second node now */
    head_ref = first.next;
     
    /* Set the next of first as null */
    first.next = null;
     
    /* Set the next of last as first */
    last.next = first;
    return head_ref;
}
 
/* UTILITY FUNCTIONS */
/* Function to add a node at the beginning
of Linked List */
function push(head_ref, new_data)
{
    var new_node = new Node();
    new_node.data = new_data;
    new_node.next = head_ref;
    head_ref = new_node;
    return head_ref;
}
 
// Function to print nodes in
// a given linked list
function printList(node)
{
    while (node != null)
    {
        document.write(node.data + " ");
        node = node.next;
    }
}
 
// Driver code
var start = null;
 
// The constructed linked list is:
// 1.2.3.4.5
start = push(start, 5);
start = push(start, 4);
start = push(start, 3);
start = push(start, 2);
start = push(start, 1);
 
document.write("Linked list before " +
               "moving first to end<br>");
printList(start);
start = moveToEnd(start);
 
document.write("<br> Linked list after moving " +
               "first to end<br>");
printList(start);
 
// This code is contributed by rdtank
 
</script>
Producción: 

Linked list before moving first to end
1 2 3 4 5 
 Linked list after moving first to end
2 3 4 5 1

 

Complejidad de tiempo: O(n) donde n es el número de Nodes en la lista enlazada dada.
 

Publicación traducida automáticamente

Artículo escrito por aganjali10 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *