Shangsilicon Valley data structure and algorithm self-study notes Chapter 3 linked list

Chapter 3 linked list

3.1 linked list

3.1.1 introduction to linked list

  • Linked lists are stored in node mode, and the storage space is not necessarily continuous
  • Each node contains a data field and a pointer field
  • Each node is not necessarily continuous storage
  • If the linked list has a leading node and a non leading node, which one to use is determined according to the demand

3.1.2 linked list CRUD

1. Create a student linked list according to the input order

/**
 * The type Single linked list.
 * @author ybs
 */
public class SingleLinkedListTest {
    public static void main(String[] args) {
        StudentNode s1 = new StudentNode(1, "jack", "c1");
        StudentNode s2 = new StudentNode(2, "york", "c1");
        StudentNode s3 = new StudentNode(3, "peter", "c1");
        StudentNode s4 = new StudentNode(4, "marry", "c1");

        SingleLinkedList singleLinkedList = new SingleLinkedList();
        singleLinkedList.addNode(s1);
        singleLinkedList.addNode(s2);
        singleLinkedList.addNode(s3);
        singleLinkedList.addNode(s4);

        singleLinkedList.listLinkedList();
    }
}

class SingleLinkedList{
    /**
     * head Head node
     */
    public StudentNode head = new StudentNode(0, "", "");

    public void addNode(StudentNode student){

        StudentNode temp = head;
        //Find the last node
        while(true){
            if(temp.next==null) {
                break;
            }
            temp = temp.next;
        }
        temp.next=student;
    }

    public void listLinkedList(){
        if(head.next==null){
            System.out.println("Empty linked list");
            return;
        }

        StudentNode temp = head.next;
        while(true){
            if(temp==null){
                break;
            }
            System.out.println(temp);
            temp = temp.next;
        }
    }

}

class StudentNode{
    public int stuNo;
    public String stuName;
    public String stuClass;
    public StudentNode next;

    public StudentNode(int stuNo, String stuName, String stuClass) {
        this.stuNo = stuNo;
        this.stuName = stuName;
        this.stuClass = stuClass;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuNo=" + stuNo +
                ", stuName='" + stuName + '\'' +
                ", stuClass='" + stuClass + '\'' +
                '}';
    }
}

2. Create a student list in numbered order

/**
 * The type Single linked list.
 * @author ybs
 */
public class SingleLinkedListTest {
    public static void main(String[] args) {
        StudentNode s1 = new StudentNode(1, "jack", "c1");
        StudentNode s2 = new StudentNode(2, "york", "c1");
        StudentNode s3 = new StudentNode(3, "peter", "c1");
        StudentNode s4 = new StudentNode(4, "marry", "c1");

        SingleLinkedList singleLinkedList = new SingleLinkedList();
/*        singleLinkedList.addNode(s1);
        singleLinkedList.addNode(s2);
        singleLinkedList.addNode(s3);
        singleLinkedList.addNode(s4);*/

        singleLinkedList.addNodeByOrder(s3);
        singleLinkedList.addNodeByOrder(s1);
        singleLinkedList.addNodeByOrder(s2);
        singleLinkedList.addNodeByOrder(s4);
        singleLinkedList.addNodeByOrder(s4);

        singleLinkedList.listLinkedList();
    }
}

class SingleLinkedList{
    /*Others are the same as 1*/

    //Add the linked list according to the serial number
    public void addNodeByOrder(StudentNode student){
        StudentNode temp = head;
        boolean flag = false;//Determine whether there are duplicate serial numbers
        //Find insertion location
        while(true){
            if(temp.next==null){
                break;
            }
            if(temp.next.stuNo > student.stuNo){
                break;
            }else if(temp.next.stuNo == student.stuNo){
                flag=true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            System.out.printf("Duplicate serial number%d,Unable to join\n",student.stuNo);
        }else{
            student.next = temp.next;
            temp.next = student;
        }
    }

}

class StudentNode{
    /*Same as 1*/
}

3. Modify linked list

/**
 * The type Single linked list.
 * @author ybs
 */
public class SingleLinkedListTest {
    public static void main(String[] args) {
        StudentNode s1 = new StudentNode(1, "jack", "c1");
        StudentNode s2 = new StudentNode(2, "york", "c1");
        StudentNode s3 = new StudentNode(3, "peter", "c1");
        StudentNode s4 = new StudentNode(4, "marry", "c1");

        SingleLinkedList singleLinkedList = new SingleLinkedList();
/*        singleLinkedList.addNode(s1);
        singleLinkedList.addNode(s2);
        singleLinkedList.addNode(s3);
        singleLinkedList.addNode(s4);*/

        singleLinkedList.addNodeByOrder(s3);
        singleLinkedList.addNodeByOrder(s1);
        singleLinkedList.addNodeByOrder(s2);
        singleLinkedList.addNodeByOrder(s4);
        singleLinkedList.addNodeByOrder(s4);
		singleLinkedList.listLinkedList();
        singleLinkedList.updateNode(new StudentNode(3, "sam", "c2"));
        singleLinkedList.listLinkedList();
    }
}

class SingleLinkedList{
    /*Others are the same as 1*/

    //Modify node
    //Find the modification according to the stuNo number of the node newStudent to be modified
    public void updateNode(StudentNode newStudent){
        if(head.next==null){
            System.out.println("Empty linked list");
            return;
        }
        StudentNode temp = head.next;
        boolean flag = false;//Determine whether the serial number is found
        while(true){
            if(temp==null){
                break;
            }
            if(temp.stuNo== newStudent.stuNo){
                flag=true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.stuName = newStudent.stuName;
            temp.stuClass = newStudent.stuClass;
        }else{
            System.out.printf("Serial number not found%d Students",newStudent.stuNo);
        }
    }

}

class StudentNode{
    /*Same as 1*/
}

3.1.3 single linked list title

1. Find the number of effective nodes of a single linked list

//Gets the length of the single linked list
public static int getLength(StudentNode head){
    if(head.next == null){
        return 0;
    }
    int length = 0;
    StudentNode temp = head.next;
    while(temp!=null){
        length++;
        temp=temp.next;
    }
    return length;
}

2. Find the penultimate node of the single lin k ed list

//Get the penultimate element of the single linked list
//1. Get the current length of the single linked list first. 2. Traverse the size index from scratch
public static StudentNode getLastIndexNode(StudentNode head, int index){
    if(head.next==null || index <= 0 || index > getLength(head)){
        return null;
    }
    int size = getLength(head);
    StudentNode temp = head.next;
    for(int i=0;i<(size-index);++i){
        temp = temp.next;
    }
    return temp;
}

3. Single linked list inversion

//Reverse single linked list
//1. Set a new head node reverseHead 2. Traverse the linked list and put the node at the front of reverseHead each time 3. Point the original head node to the next node of the new head node
public static void reverseLinkedList(StudentNode head){
    //If it is empty or there is only one node, it will be returned directly
    if(head.next==null||head.next.next==null){
        return;
    }
    StudentNode temp = head.next;//Loop pointer
    StudentNode next = null;//Pointer to the next in the current loop
    StudentNode reverseHead = new StudentNode(0, "", "");//New header node
    while(temp!=null){
        next = temp.next;
        temp.next = reverseHead.next;
        reverseHead.next = temp;
        temp = next;
    }
    head.next = reverseHead.next;
}

4. Print a single linked list from end to end

//Print a single linked list from end to end
public void reverseListLinkedList(){
    if(head.next==null){
        return;
    }
    Stack<StudentNode> stack = new Stack<>();
    StudentNode temp = head.next;
    while(temp!=null){
        stack.push(temp);
        temp = temp.next;
    }
    while(stack.size()>0){
        System.out.println(stack.pop());
    }
}

5. Merge two ordered single linked lists, and they will remain ordered after merging

//Merge two ordered single linked tables, and the merge is still ordered
public static SingleLinkedList mergeLinkedList(SingleLinkedList sglList1, SingleLinkedList sglList2){
    SingleLinkedList singleLinkedList = new SingleLinkedList();
    StudentNode list1 = sglList1.head;
    StudentNode list2 = sglList2.head;
    StudentNode newList = new StudentNode(0, "", "");
    if(list1.next==null){
        newList.next = list2.next;
        singleLinkedList.head = newList;
        return singleLinkedList;
    }else if(list2.next==null){
        newList.next  = list1.next;
        singleLinkedList.head = newList;
        return singleLinkedList;
    }
    StudentNode temp1 = list1.next;
    StudentNode temp2 = list2.next;
    StudentNode tempNewList = newList;
    while (temp1!=null && temp2!=null){
        if(temp1.stuNo< temp2.stuNo){
            tempNewList.next=temp1;
            tempNewList = tempNewList.next;
            temp1 = temp1.next;
        }else{
            tempNewList.next=temp2;
            tempNewList = tempNewList.next;
            temp2 = temp2.next;
        }
    }
    if (temp1==null){
        tempNewList.next = temp2;
    }else{
        tempNewList.next = temp1;
    }
    singleLinkedList.head = newList;
    return singleLinkedList;
}

3.2 bidirectional linked list

3.2.1 introduction to bidirectional linked list

  • A single linked list can only be searched in one direction, and a two-way linked list can be searched forward and backward
  • The nodes of a single linked list cannot be deleted, and the nodes of a double linked list can be deleted

3.2.2 two way linked list CRUD

public class DoubleLinkedListTest {
    public static void main(String[] args) {
        StudentNode2 s1 = new StudentNode2(1, "jack", "c1");
        StudentNode2 s2 = new StudentNode2(2, "york", "c1");
        StudentNode2 s3 = new StudentNode2(3, "peter", "c1");
        StudentNode2 s4 = new StudentNode2(4, "marry", "c1");
        StudentNode2 s5 = new StudentNode2(5, "sam", "c2");

        DoubleLinkedList doubleLinkedList = new DoubleLinkedList();
        doubleLinkedList.addNode(s1);
        doubleLinkedList.addNode(s2);
        doubleLinkedList.addNode(s3);
        doubleLinkedList.addNode(s4);
        doubleLinkedList.addNode(s5);

        //doubleLinkedList.updateNode(new StudentNode2(3, "peter", "c2"));
        //doubleLinkedList.deleteNode(3);
        doubleLinkedList.listLinkedList();

    }
}

class DoubleLinkedList{
    /**
     * head Head node
     */
    public StudentNode2 head = new StudentNode2(0, "", "");

    public void addNode(StudentNode2 student){

        StudentNode2 temp = head;
        //Find the last node
        while(true){
            if(temp.next==null) {
                break;
            }
            temp = temp.next;
        }
        temp.next=student;
        student.previou = temp;
    }

    public void listLinkedList(){
        if(head.next==null){
            System.out.println("Empty linked list\n");
            return;
        }

        StudentNode2 temp = head.next;
        while(true){
            if(temp==null){
                break;
            }
            System.out.println(temp);
            temp = temp.next;
        }
    }

    //Delete Vertex 
    //Delete node by number
    public void deleteNode(int stuNo){
        StudentNode2 temp = head.next;
        boolean flag = false;//Determine whether the node is found
        while(true){
            if(temp==null){
                break;
            }
            if(temp.stuNo==stuNo){
                flag=true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.next.previou = temp.previou;
            temp.previou.next = temp.next;
        }else{
            System.out.printf("No found%d Node of",stuNo);
        }
    }

    //Modify node
    //Find the modification according to the stuNo number of the node newStudent to be modified
    public void updateNode(StudentNode2 newStudent){
        if(head.next==null){
            System.out.println("Empty linked list");
            return;
        }
        StudentNode2 temp = head.next;
        boolean flag = false;//Determine whether the serial number is found
        while(true){
            if(temp==null){
                break;
            }
            if(temp.stuNo== newStudent.stuNo){
                flag=true;
                break;
            }
            temp = temp.next;
        }
        if(flag){
            temp.stuName = newStudent.stuName;
            temp.stuClass = newStudent.stuClass;
        }else{
            System.out.printf("Serial number not found%d Students",newStudent.stuNo);
        }
    }
}

class StudentNode2 {
    public int stuNo;
    public String stuName;
    public String stuClass;
    public StudentNode2 next;
    public StudentNode2 previou;

    public StudentNode2(int stuNo, String stuName, String stuClass) {
        this.stuNo = stuNo;
        this.stuName = stuName;
        this.stuClass = stuClass;
    }

    @Override
    public String toString() {
        return "Student{" +
                "stuNo=" + stuNo +
                ", stuName='" + stuName + '\'' +
                ", stuClass='" + stuClass + '\'' +
                '}';
    }
}

3.3 circular linked list and Joseph problem

3.3.1 application scenario of unidirectional ring linked list

Josephu (Joseph, Joseph Ring) problem

3.3.2 construction and traversal of one-way ring linked list

1. Construction ideas

First create a first node and form a ring. Every time a new node is added, the node will be added to the existing ring linked list

2. Traversal idea

First, let an auxiliary pointer cur point to first, and then traverse the circular linked list through while. When cur.next=first, it ends

3. Realize

public class JosephuProblemTest {
    public static void main(String[] args) {
        CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
        circleSingleLinkedList.addGirl(5);
        circleSingleLinkedList.listGirls();
    }
}

class CircleSingleLinkedList{
    public Girl first = null;

    public CircleSingleLinkedList(){}

    public void addGirl(int num){
        if (num<1){
            System.out.println("num Non conformity");
            return;
        }
        Girl curGirl = null;
        for(int i=1;i<=num;++i){
            Girl girl = new Girl(i);
            if (i==1){
                first = girl;
                curGirl = first;
                girl.setNext(first);
            }else{
                curGirl.setNext(girl);
                girl.setNext(first);
                curGirl = girl;
            }
        }
    }

    public void listGirls(){
        if (first==null){
            System.out.println("Empty table");
            return;
        }
        Girl curGirl = first;
        while(true){
            System.out.println("Girl "+curGirl.getId());
            if(curGirl.getNext()==first){
                break;
            }
            curGirl = curGirl.getNext();
        }
    }
}

class Girl{
    private int id;
    private Girl next;

    public Girl(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public Girl getNext() {
        return next;
    }

    public void setNext(Girl next) {
        this.next = next;
    }
}

3.3.3 problem realization

Idea: n how many people are there; K means counting off from the k-th person; m means several numbers at a time

  1. You need to create an auxiliary pointer helper, which should point to the last node of the ring linked list in advance
  2. Before counting, let the first and helper move k-1 times at the same time
  3. When counting, let the first and helper move m-1 times at the same time
  4. At this time, the node pointed to by first is out of the loop
/**
     * Joseph problem realization
     *
     * @param startId  Indicates the number from which to start
     * @param countNum It means counting to a few laps at a time
     * @param sumNum   Indicates how many children there were at first
     */
public void josephuCountGirl(int startId,int countNum,int sumNum){
    if (first==null || startId < 1 || startId > sumNum){
        System.out.println("Linked list or input exception");
        return;
    }
    Girl helper = first;
    //Move the helper to the last node
    while(true){
        if(helper.getNext()==first){
            break;
        }
        helper = helper.getNext();
    }
    //Move first to the starting node and the helper to the previous node of first
    for(int i=0;i<startId-1;++i){
        first = first.getNext();
        helper = helper.getNext();
    }
    //Count and circle
    while(true){
        //When first==helper, it means that there is only one node left in the circle. Jump out
        if (first==helper){
            break;
        }
        //Count
        for (int i=0;i<countNum-1;++i){
            first = first.getNext();
            helper = helper.getNext();
        }
        System.out.printf("%d Out of circle\n",first.getId());
        first = first.getNext();//first moves to the next node of the out of loop node
        helper.setNext(first);//helper.next points to first, and the out of loop node is moved out of the linked list
    }
    System.out.printf("Last remaining%d\n",first.getId());
}

Tags: Java data structure linked list Singly Linked List

Posted on Sun, 05 Dec 2021 20:37:55 -0500 by elflacodepr