Home > Java > javaTutorial > body text

Example analysis of linked lists in Java

PHPz
Release: 2023-05-31 17:13:07
forward
707 people have browsed it

Question 1

Example analysis of linked lists in Java

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public int getDecimalValue(ListNode head) {
        int[] arr = new int[31];
        int index = 0;
        int ans = 0;
        while(head!=null){
            arr[index] = head.val;
            index++;
            head = head.next;
        }
        for(int i = 0;i<index;i++){
            if(arr[i]==1){
                ans+=(1<<(index-1-i));
            }
        }
        return ans;
    }
}
Copy after login

Question 2

Example analysis of linked lists in Java

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        int index = 0;
        ListNode h = head;
        while(head!=null){
            head = head.next;
            index++;
        }
        int[] arr = new int[index];
        while(h!=null){
            arr[index-1] = h.val;
            index--;
            h = h.next;
        }
        return arr;
    }
}
Copy after login

Question 3

Example analysis of linked lists in Java

Solution

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode node = new ListNode(-1);
        ListNode ans = node;
        while(l1!=null&&l2!=null){
            if(l1.val<=l2.val){
                node.next = l1;
                l1 = l1.next;
            }else{
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        if(l1!=null){
            node.next = l1;
        }
        if(l2!=null){
            node.next = l2;
        }
        return ans.next;
    }
}
Copy after login

The above is the detailed content of Example analysis of linked lists in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template