目录
8.剑指 Offer 52. 两个链表的第一个公共节点(这个很经典,双指针)
前言
剑指offer中的所有链表题都做一遍。
还有快慢指针的题!
0812完成!
明天要完成所有的tree

1.剑指 Offer 35. 复杂链表的复制
2.二叉搜索树和双向链表
class Solution {
// 标准的树型的结构,需要转换成排序的 且双向链表
// 而且修安排就地完成转换操作。 left为前驱节点, right 为后置的节点
// 返回第一个节点
// 解法:中序遍历:
// 设前驱节点 pre 和当前节点 cur ,不仅应构建 pre.right = cur ,也应构建 cur.left = pre 。
// 因为,pre.right 前置的右 指向当前的节点, 当前节点的左,指向前置
// 标准的双向链表
// 循环链表最后在考虑
// 循环链表: 设链表头节点 head 和尾节点 tail ,则应构建 head.left = tail 和 tail.right = head 。
Node pre ,head = null;
public Node treeToDoublyList(Node root) {
if(root == null) return null;
dfs(root);
// 头的左指针指向他的尾部
head.left = pre;
// 尾结点的右指针指向头
pre.right = head;
return head;
}
// 这个头和尾怎么看呢,因为是dfs, 所以最后会回到head 也就是头结点啊, 也就是head,但是head的pre 是什么呢
// 因为如果为空 那么head = cur,但是显然不是,所以 这个pre 就是执行到了末尾节点的,然后一层一层的都return了
void dfs(Node cur) {
if(cur == null) return;
dfs(cur.left);
if(pre != null) {
pre.right = cur;
}
else
{
head = cur;
}
cur.left = pre;
pre = cur;
dfs(cur.right);
}
}
3.剑指 Offer 06. 从尾到头打印链表
4.剑指 Offer 18. 删除链表的节点(双指针)
// 删除节点的话,
public ListNode deleteNode(ListNode head, int val) {
// 处理头结点
if(head.val == val) return head.next;
// pre 和cur指针
ListNode pre = head, cur = head.next;
while(cur != null && cur.val != val) {
pre = cur;
cur = cur.next;
}
if(cur != null) pre.next = cur.next;
return head;
}
5链表中倒数第k个节点(快慢指针)
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode former = head, latter = head;
for(int i = 0; i < k; i++)
former = former.next;
while(former != null) {
former = former.next;
latter = latter.next;
}
return latter;
}
}
6.反转链表(双指针)
递归
7.合并两个排序的链表
public ListNode gf_mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dum = new ListNode(0), cur = dum;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = l1 != null ? l1 : l2;
return dum.next;
}
8.剑指 Offer 52. 两个链表的第一个公共节点(这个很经典,双指针)
// 202108在刷:
public ListNode getIntersectionNode_08(ListNode headA, ListNode headB) {
// 两个链表的第一个公共节点
// 如果不相交,那么返回NUll
// 可以两个都遍历一遍,拿到长度之后长的多走两步这种解法
// 循环一遍放到hashSET也行啊
ListNode tempA = headA;
ListNode tempB = headB;
int sizeA = 0;
int sizeB = 0;
while(tempA != null){
tempA = tempA.next;
sizeA++;
}
while(tempB != null){
tempB = tempB.next;
sizeB++;
}
// 绝对值
int distance = sizeA - sizeB > 0 ? sizeA - sizeB : sizeB - sizeA;
//让长的多走两步
tempA = headA;
tempB = headB;
if(sizeA - sizeB > 0){
//A 长
for(int i =0; i< distance;i++){
tempA=tempA.next;
}
} else{
for(int i =0; i< distance;i++){
tempB=tempB.next;
}
}
// 同时循环
while(tempA !=null && tempB !=null){
if(tempA == tempB){
return tempA;
}
tempA = tempA.next;
tempB = tempB.next;
}
return null;
}
官方题解:双指针法
365




被折叠的 条评论
为什么被折叠?



