📌  相关文章
📜  用于在链表中制作中间节点头部的Java程序

📅  最后修改于: 2022-05-13 01:57:45.159000             🧑  作者: Mango

用于在链表中制作中间节点头部的Java程序

给定一个单链表,找到链表的中间节点,并将链表的中间节点设置在链表的开头。
例子:

Input: 1 2 3 4 5 
Output: 3 1 2 4 5

Input: 1 2 3 4 5 6
Output: 4 1 2 3 5 6 

https://media.geeksforgeeks.org/wp-content/uploads/Capturedsdw.png

这个想法是首先使用两个指针找到链表的中间,第一个一次移动一个,第二个一次移动两个。当第二个指针到达终点时,第一个到达中间。我们还跟踪第一个指针的前一个,以便我们可以将中间节点从其当前位置移除并使其成为头部。

Java
// Java program to make middle node 
// as head of Linked list
public class GFG 
{     
    // Link list node 
    static class Node 
    {
        int data;
        Node next;
        Node(int data)
        {
            this.data = data;
            next = null;
        }
    }
      
    static Node head;
      
    /* Function to get the middle and 
       set at beginning of the linked list*/
    static void setMiddleHead()
    {
        if (head == null)
            return;
       
        // To traverse list nodes one 
        // by one
        Node one_node = head;
       
        // To traverse list nodes by 
        // skipping one.
        Node two_node = head;
       
        // To keep track of previous of middle
        Node prev = null;
        while (two_node != null && 
               two_node.next != null) 
        {     
            // For previous node of middle node 
            prev = one_node;
       
            // Move one node each time
            two_node = two_node.next.next;
       
            // Move two node each time
            one_node = one_node.next;
        }
       
        // Set middle node at head 
        prev.next = prev.next.next;
        one_node.next = head;
        head = one_node;
    }
       
    // To insert a node at the beginning 
    // of linked list.
    static void push(int new_data)
    {
        // Allocate node 
        Node new_node = new Node(new_data);
       
        // Link the old list off the new node 
        new_node.next = head;
       
        // Move the head to point to the 
        // new node 
        head = new_node;
    }
       
    // A  function to print a given linked list
    static void printList(Node ptr)
    {
        while (ptr != null) 
        {
            System.out.print(ptr.data + " ");
            ptr = ptr.next;
        }
        System.out.println();
    }
       
    // Driver function
    public static void main(String args[])
    {
        // Create a list of 5 nodes
        head = null;
        int i;
        for (i = 5; i > 0; i--)
            push(i);
          
        System.out.print(" list before: ");
        printList(head);
       
        setMiddleHead();
       
        System.out.print(" list After:  ");
        printList(head);
      
    }
}
// This code is contributed by Sumit Ghosh


输出:

list before: 1 2 3 4 5
list After : 3 1 2 4 5 

请参考完整文章在链表中制作中间节点头以获取更多详细信息!