数据结构与算法(五)

49 阅读1分钟

1、剑指 Offer 25 合并两个排序的链表

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 限制:

0 <= 链表长度 <= 1000

/**
 * 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) {
        
        if(l1 == null && l2 == null)
            return l1;
        if(l1 == null && l2 != null)
            return l2;
        if(l1 != null && l2 == null)
            return l1;
       
        ListNode prehead = new ListNode(-1);
        ListNode preNext = prehead;

        while(l1 != null  && l2 != null){
            if(l1.val > l2.val){
                preNext.next = l2;
                l2 = l2.next;
            }   
            else {
                preNext.next = l1;
                l1 = l1.next;
            }
            preNext = preNext.next;  
        }
       
        preNext.next = l1 == null ? l2 : l1;
        return prehead.next;
    }
}

2、剑指 Offer 24 反转链表

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。

示例:

输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL  

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
       if(head == null)
            return head;
       ListNode newHead = head;
       ListNode p = head.next;
       ListNode p1 = p;
       newHead.next = null;
        while(p != null && p1 != null){
            p1 = p.next;
            p.next = newHead;
            newHead = p;
            p = p1;
        }

        return newHead;
    }
}