「算法」反转链表 & 相交链表

160 阅读1分钟

00206 反转链表

题目描述

反转一个单链表.

示例:

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

力扣地址

解题报告

迭代实现

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

  • 假设存在链表 1 → 2 → 3 → Ø,我们想要把它改成 Ø ← 1 ← 2 ← 3。
  • 在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用。
/**
 * 微信公众号"小猿刷题"
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode target = null;
        ListNode current = head;
        while (current != null) {
            ListNode nextTemp = current.next;
            current.next = target;
            target = current;
            current = nextTemp;
        }
        return target;
    }
}

递归实现

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

/**
 * 微信公众号"小猿刷题"
 * 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 || head.next == null) {
            return head;
        }
        ListNode target = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return target;
    }
}

小猿刷题

00160 相交链表

题目描述

编写一个程序,找到两个单链表相交的起始节点。

力扣地址

解题报告

本题解由微信公众号小猿刷题提供, 错误之处, 欢迎指正.

/**
 * 微信公众号"小猿刷题"
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null){
             return null;
        }
        ListNode l1 = headA;
        ListNode l2 = headB;
        while(l1 != l2){
            l1 = l1 == null ? headB: l1.next;
            l2 = l2 == null ? headA: l2.next;
        }
        return l1;
    }
}

小猿刷题