剑指Offer之Java算法习题精讲链表专题篇

题目一

剑指Offer之Java算法习题精讲链表专题篇_第1张图片

 解法

/**
 * 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 
 

题目二

剑指Offer之Java算法习题精讲链表专题篇_第2张图片

 解法

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

题目三

剑指Offer之Java算法习题精讲链表专题篇_第3张图片

解法

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

到此这篇关于剑指Offer之Java算法习题精讲链表专题篇的文章就介绍到这了,更多相关Java 链表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(剑指Offer之Java算法习题精讲链表专题篇)