24 两两交换链表中的节点
题目
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
思路
三指针,建立虚拟头结点
递归emmm,
代码
三指针
//int val;ListNode next;ListNode(); ListNode(int val); ListNode(int val, ListNode next) class Solution { public ListNode swapPairs(ListNode head) { ListNode dummyhead = new ListNode(-1); dummyhead.next = head; ListNode pre = dummyhead; ListNode cur = head; if (head == null)return head; while (cur.next != null){ ListNode tmp = cur.next; cur.next = tmp.next; tmp.next = cur; pre.next = tmp; if(cur.next == null)break; pre = cur; cur = cur.next; } return dummyhead.next; } }
递归
class Solution { public ListNode swapPairs(ListNode head) { if (head == null || head.next ==null) return head; ListNode cur = swapPairs(head.next.next); ListNode tmp = head.next; head.next = cur; tmp.next = head; return tmp; } }
过程
执行错误
tmp(=cur.next) 在哪儿声明纠结了一下,结果没删干净
递归
看了下另一题的递归,勉强照猫画虎
-
line 4 head.next 改为head.next.next,此时还未调整,一次要跳两格
-
line 6 head.next = tmp.next改为head.next = cur 不是很懂, 形参?tmp.next不=cur吗?
-
line8 return head; return head.next 改为 return tmp;
题解笔记
总结
19 删除链表的倒数第 N 个结点
题目
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
思路
快慢指针,好像摸过(快慢指针还是双指针来着)
代码
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummyhead = new ListNode(-1); dummyhead.next = head; ListNode pre = dummyhead ; //删掉的是pre.next ListNode cur = head; for(int i = 1 ; i<n ; i++){ cur = cur.next; } while (cur.next != null){ cur = cur.next; pre = pre.next; } pre.next = pre.next.next; return dummyhead.next; } }
过程
执行错误
声明dummyhead 后忘了dummyhead.next =head
return head 改为 return dummyhead.next;
题解笔记
总结
return要注意,注意return.
面试题 02.07. 链表相交
题目
给你两个单链表的头节点 headA
和 headB
,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null
。
思路
emmm原来题目说的m、n没给啊。。。。
看题解去了,那个 nodeA == nodeB 不知道为啥能比较,为啥相等就代表后面全相等
代码
过程
执行错误
题解笔记
这代码好炫酷。。
把两段路加起来,先把别人的路走了,再走自己的路,A走B-A路,B走A-B路,这样总长度就相等了,末段就是自己的路和别人的路的比较 即 a + (b-c) + c 与 b + (a - c) + c 前段都是a+b-c,后段都是c
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { ListNode A = headA, B = headB; while (A != B) { A = A != null ? A.next : headB; B = B != null ? B.next : headA; } return A; } }
line4,为什么能直接比较这个呢,指针相等是怎么判断的,因为之前都是比较的val 不行,还是理解不了,那个B 指针相等,只能比值,咋能比地址呢
java的应该就是比的值} 那又有新的问题,这个每次比较的时候岂不是把 A、B 之后的整个链表都比较了一遍?
总结
142 环形链表Ⅱ
题目
给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
思路
判断相遇没思路,看题解了
题解倒是看得懂,明天看看这类题的视频讲解。
代码
struct ListNode *detectCycle(struct ListNode *head) { struct ListNode* fast = head; struct ListNode* slow = head; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) { while (fast != head) { fast = fast->next; head = head->next; } return fast; } } return NULL; }
过程
执行错误
题解笔记
总结
明天看视频讲解