题目
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
两个链表相交节点https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
* 可以理解成两个人速度一致, 走过的路程一致。那么肯定会同一个时间点到达终点。
* 走到尽头见不到你,于是走过你来时的路,等到相遇时才发现,你也走过我来时的路。
* 给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//边界限制
if (headA == null || headB == null) {
return null;
}
ListNode preA=headA,preB=headB;
while (preA!= preB) {
preA = preA == null ? headB : preA.next;
preB = preB == null ? headA : preB.next;
}
return preA;
}
}
复杂链表的复制https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/
/*
// Definition for a Node.
class Node {
int val;
Node next;
Node random;
public Node(int val) {
this.val = val;
this.next = null;
this.random = null;
}
}
*/
class Solution {
public Node copyRandomList(Node head) {
//边界限制
if (head == null) {
return null;
}
//声明一个hashSet 存储新老节点对应关系
Map<Node, Node> map = new HashMap<>();
Node node = head;
while (node != null) {
//k 原始节点 v 新节点数值,无指向
map.put(node, new Node(node.val));
node = node.next;
}
//整理新节点指向问题
node = head;
while (node != null) {
map.get(node).next=map.get(node.next);
map.get(node).random=map.get(node.random);
node = node.next;
}
return map.get(head);
}
}
反转单向链表https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/submissions/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//时间复杂度为 O(N) 间复杂度为 O(1)
ListNode cur = head, pre = null;
//边界限制
if (head == null) {
return null;
}
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}