[Datastructure] Some useful methods about into list (2)

Source: Internet
Author: User

Method 1: Add one list into the other list.

For example, if list1is {22, 33, 44, 55} And list2 is {66, 77, 88, 99}, then append (list1, list2) will change list1to {22, 33, 44, 55, 44, 66, 77, 88, 99 }.

static void append(Node list1, Node list2) {if (list1 == null) {throw new IllegalArgumentException();}while (list1.next != null) {list1 = list1.next;}list1.next = list2;}

The output is as follows:



Method2: gets a new list combined by two list

For example, if list1 is {22, 33, 44, 55} And list2 is {66, 77, 88, 99}, then Concat (list1, list2) will return the new list {22, 33, 44, 55, 44, 55, 66, 77, 88 }.

Note that the three lists shocould be completely independent of each other. Changing one list shoshould have no effect upon the others.

static Node concat(Node list1, Node list2) {Node list3 = new Node(0);Node p = list1;Node q = list3;while(p != null){q.next = new Node(p.data);p = p.next;q = q.next;}    p = list2;    while(p != null)    {    q.next = new Node(p.data);    q = q.next;    p = p.next;    }return list3.next;}

The output is as follows:


Method 3: replace the value of element number I with x

Void set (node list, int I, int X)

For example, if list is {22, 33, 44, 55, 66, 77, 88, 99}, then set (list, 2, 50) will change list to {22, 33, 50, 55, 66, 44, 88, 99}

Solution 1:static void set(Node list, int i, int x) {Node p = list;int count = 0;while (p != null) {if (count == i) {p.data = x;break;}p = p.next;count++;}}Solution2:static void set(Node list, int i, int x) {if (i < 0) {throw new IllegalArgumentException();}for (int j = 0; j < i; j++) {if (list == null) {throw new IllegalStateException();}list = list.next;}list.data = x;}

The output is as follows:




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.