Table of Contents
Question 3
Home Java javaTutorial Example analysis of linked lists in Java

Example analysis of linked lists in Java

May 31, 2023 pm 05:13 PM
java

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;
    }
}

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;
    }
}

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;
    }
}

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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1510
276
Fixed: Windows Update Failed to Install Fixed: Windows Update Failed to Install Aug 08, 2025 pm 04:16 PM

RuntheWindowsUpdateTroubleshooterviaSettings>Update&Security>Troubleshoottoautomaticallyfixcommonissues.2.ResetWindowsUpdatecomponentsbystoppingrelatedservices,renamingtheSoftwareDistributionandCatroot2folders,thenrestartingtheservicestocle

How to use a while loop in Java How to use a while loop in Java Aug 08, 2025 pm 04:04 PM

AwhileloopinJavarepeatedlyexecutescodeaslongastheconditionistrue;2.Initializeacontrolvariablebeforetheloop;3.Definetheloopconditionusingabooleanexpression;4.Updatethecontrolvariableinsidethelooptopreventinfinitelooping;5.Useexampleslikeprintingnumber

What is the process of serialization for a Java object? What is the process of serialization for a Java object? Aug 08, 2025 pm 04:03 PM

Javaserializationconvertsanobject'sstateintoabytestreamforstorageortransmission,anddeserializationreconstructstheobjectfromthatstream.1.Toenableserialization,aclassmustimplementtheSerializableinterface.2.UseObjectOutputStreamtoserializeanobject,savin

What is a HashMap in Java? What is a HashMap in Java? Aug 11, 2025 pm 07:24 PM

AHashMapinJavaisadatastructurethatstoreskey-valuepairsforefficientretrieval,insertion,anddeletion.Itusesthekey’shashCode()methodtodeterminestoragelocationandallowsaverageO(1)timecomplexityforget()andput()operations.Itisunordered,permitsonenullkeyandm

How to create and use an array in Java How to create and use an array in Java Aug 11, 2025 pm 04:00 PM

TocreateanduseanarrayinJava,firstdeclarethearraywiththedatatypeandsquarebrackets,theninstantiateitwiththenewkeywordorinitializeitdirectlywithvalues;1.DeclareandcreateanarrayusingdataType[]arrayName=newdataType[size];or2.InitializedirectlywithdataType

How do you create a thread in Java? How do you create a thread in Java? Aug 11, 2025 pm 01:34 PM

YoucancreateathreadinJavabyextendingtheThreadclassorimplementingtheRunnableinterface.2.ExtendingThreadinvolvescreatingaclassthatoverridestherun()methodandcallingstart()onaninstance.3.ImplementingRunnablerequiresdefiningtherun()methodinaclassthatimple

python argparse required argument example python argparse required argument example Aug 11, 2025 pm 09:42 PM

When using the argparse module, the parameters that must be provided can be achieved by setting required=True. 1. Use required=True to set optional parameters (such as --input) to be required. If not provided when running the script, an error will be reported; 2. Position parameters are required by default, and there is no need to set required=True; 3. It is recommended to use position parameters for necessary parameters. Occasionally, the optional parameters of required=True are used to maintain flexibility; 4. required=True is the most direct way to control parameters. After use, the user must provide corresponding parameters when calling the script, otherwise the program will prompt an error and exit.

How to use a Set in Java How to use a Set in Java Aug 11, 2025 am 11:57 AM

ChoosetheappropriateSetimplementation:useHashSetforfastoperationswithoutorder,LinkedHashSetforinsertionorder,andTreeSetforsortedorder.2.Addelementswithadd()andremovewithremove(),whereadd()returnsfalseiftheelementisalreadypresent.3.Checkforelementsusi

See all articles