Data structure of the chain Surface test Summary (a)--find one-way linked list of intermediate nodes, the penultimate K node __ data structure

Source: Internet
Author: User
Tags throw exception

Date:2016-08-18 9:12:22
Title: Data structure of the chain surface question Summary (i)-Find the middle node of one-way linked list, reciprocal k node
Categories: Data structure

Copyright NOTICE: This site adopts an open [knowledge sharing signature-non-commercial use-the same way sharing license agreement] for licensing

The code that appears in all of the articles will appear in my GitHub, the name can be found in the class name, and the folders in my GitHub will be added to the catalog notes.

This article mainly discusses the application of one-way linked list, general structure, see article directory structure. And in the method involved, can not use the container to store data, as far as possible. Each series of reference materials, in the number of the largest article, if it is unique to this article, please see the article at the end of the reference. the creation and traversal of one-way linked lists (most basic, common sense knowledge)

/**
 * Defines one-way list
 * 
 * @author xinpan
 * * 
 /Public
class Node {
    //records the value of the list
    int record;
    Record the reference node next for the next node of the current node
    ;

    ------getter&setter-------------Public
    int Getrecord () {return record
        ;
    }

    public void Setrecord (int record) {
        This.record = record;
    }

    Public Node GetNext () {return
        next;
    }

    public void Setnext (Node next) {
        this.next = next;
    }

    Public Node (int record) {
        super ();
        This.record = record;
    }
}
/**
 * Traverse one-way link list
 * * 
 @author Xinpan * */Public
class Recustionallelementoflinkedlist {

    // Outputs all node contents public
    static void Printallelements (node head) {while

        != null) {

            System.out.println ( Head.getrecord ());

            Head = Head.getnext ();
        }
    }

    Gets the length of the specified list public
    static int sizes (Node head) {
        int length = 0;
        if (head = = null) return
            length;
        while (head!= null) {
            length++;
            Head = Head.getnext ();
        }
        return length;
    }
}
find the reciprocal K-knot in a single list (sword refers to offer, title)

Ideas:

1, taking into account the nodes in the list to the array, and then through the array to get the length-k bit elements, but this method needs to put all the nodes in the array, wasting memory

2, since the use of the container to store the node this method is denied, then by what way can let it get the penultimate K node

3, take into account not to change the structure of the list itself, without the use of containers, you can use the "pointer" to complete this problem

4, you can traverse two times linked list, get to the total length of the linked list, then traverse again, traversing to the first length-k node, and then return, but this method consumes too much

5, can use two "pointers" directly in the linked list, let a foot mark move to the K-bit node and then move along with the first "pointer" when the following "pointer" reaches the last node of the list, returning the node corresponding to the previous "pointer"

Illustration: Example-Gets the penultimate node

public class Findreciprocalelementoflinkedlist {/** * Find the reciprocal K-bit node of a one-way list * @param head node * @param k  The penultimate * @return/public static node find (node head, int k) {//If the header node is empty or k=0, throw the exception if (head = = NULL | |

        K = = 0) throw new runtimeexception ("Check your parms that is sent to");
        Declares two variables to record the reference node first = head of two nodes;

        Node second = head;

            Let second "pointers" move backwards k-1 bit for (int i = 1; i < K; i++) {second = Second.getnext ();
                        Note: The value of K may be larger than the length of the list, so throw the exception if (second = null) throw the new RuntimeException (
        "The k is more than the size to this list"); ///Move two node references together until the second node reference arrives at the last node of the list while (Second.getnext ()!= null) {first = First.getnext (
            );
        Second = Second.getnext ();

  //Returns the first node reference, that is, the reciprocal K-node return.  }

}
 

Test code:

public class Reverselinkedlisttest {public

    static void Main (string[] args) {
        node Node1 = new Node (1);
        Node Node2 = new node (2);
        Node Node3 = new node (3);
        Node Node4 = new node (4);
        Node NODE5 = new node (5);
        Node Node6 = new node (6);

        Node1.setnext (node2);
        Node2.setnext (NODE3);
        Node3.setnext (NODE4);
        Node4.setnext (NODE5);
        Node5.setnext (NODE6);

        System.out.println (Findreciprocalelementoflinkedlist.find (Node1, 2)
                . Getrecord ());
    }


Run Result:

finding intermediate nodes in a one-way list

Ideas:

1, we can inherit the idea of using a double pointer in the previous question, so as to save memory, but also to improve efficiency

2, let a pointer move one at a time, another pointer to move two bits at a time, when the moving span of a large pointer to the end, the previous pointer to the corresponding node is the middle node.

Graphic:

Code implementation:

public class Findthemidelement {public

    static node Findmidnode (node Head) {

        //Judge Head is empty, is an empty throw exception
        if (head = = n ull)
            throw new RuntimeException ("Header node is empty");

        Declare two variables to store two "pointers" and have them point to node first = head
        ;
        Node second = head;

        While the following pointer points to a node that is not empty and the next node is not empty, while
        (second!= null && second.getnext ()!= null) {

            //Let the previous pointer move one at a time. The back pointer moves two first
            = First.getnext () at a time.
            Second = Second.getnext (). GetNext ();

        The pointer to the end of the description is at the bottom, and returns the previous pointer to the first
        ;

Test code: When the number of nodes is Cardinal:

public class Reverselinkedlisttest {

    /**
     * @param args
     *
    /public static void main (string[] args) {
        Node Node1 = new node (1);
        Node Node2 = new node (2);
        Node Node3 = new node (3);
        Node Node4 = new node (4);
        Node NODE5 = new node (5);

        Node1.setnext (node2);
        Node2.setnext (NODE3);
        Node3.setnext (NODE4);
        Node4.setnext (NODE5);

        System.out.println (Findthemidelement.findmidnode (Node1). Getrecord ());
    }


Run Result:

When the number of nodes is even:

public class Reverselinkedlisttest {

    /**
     * @param args
     *
    /public static void main (string[] args) {
        Node Node1 = new node (1);
        Node Node2 = new node (2);
        Node Node3 = new node (3);
        Node Node4 = new node (4);
        Node NODE5 = new node (5);
        Node Node6 = new node (6);

        Node1.setnext (node2);
        Node2.setnext (NODE3);
        Node3.setnext (NODE4);
        Node4.setnext (NODE5);
        Node5.setnext (NODE6);

        System.out.println (Findthemidelement.findmidnode (Node1). Getrecord ());
    }


Run Result:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.