链表入门题目

1.链表的反转:给出关联列表的头结点,请你反转链表——>力扣206

    //单链表定义
    public static class ListNode{
        int value;
        public ListNode next;
        public ListNode(){}
        public ListNode(int value){
            this.value = value;
        }
        public ListNode(int value,ListNode next){
            this.value = value;
            this.next = next;
        }
    }
    class Solution{
        public static ListNode reverseList(ListNode head){
            ListNode pre = null;
            ListNode next = null;
            while (head.next != null){
                next = head.next;
                head.next = pre;
                pre = head;
                head = next;
            }
            return pre;
        }
    }

2.合并两个有序链表

    public static class ListNode{
        int value;
        public ListNode next;
        public ListNode(){}
        public ListNode(int value){
            this.value = value;
        }
        public ListNode(int value,ListNode next){
            this.value = value;
            this.next = next;
        }
    }

    public static ListNode mergeTwoList(ListNode head1,ListNode head2){
        if (head1 == null || head2 == null){
            return head1 == null ? head2 : head1;
        }
        else {
            ListNode head = head1.value <= head2.value ? head1: head2;
            ListNode cur1 = head.next;
            ListNode cur2 = head1.value == head.value ? head2 : head1;
            ListNode pre = head;
            while (cur1 != null || cur2 != null){
                if (cur1.value <= cur2.value){
                    pre.next = cur1;
                    cur1 = cur1.next;
                }else {
                    pre.next = cur2;
                    cur2 = cur2.next;
                }
                pre = pre.next;
            }
            pre.next = cur1.value <= cur2.value ? cur2 : cur1;
            return head;
        }
    }

你可能感兴趣的:(链表,java,算法)