代码随想录算法训练营第四天

编程入门 行业动态 更新时间:2024-10-20 11:33:58

代码随想录<a href=https://www.elefans.com/category/jswz/34/1770096.html style=算法训练营第四天"/>

代码随想录算法训练营第四天

链表相关

24. 两两交换链表中的节点

参考文章
题目连接

思路

个人题解

class Solution {public ListNode swapPairs(ListNode head) {ListNode dummyPoint = new ListNode();dummyPoint.next = head;ListNode cur = dummyPoint;ListNode temp;ListNode first;ListNode second;while (cur.next != null && cur.next.next != null) {temp = cur.next.next.next;first = cur.next;second = cur.next.next;second.next = first;first.next = temp;cur.next = second;cur = first;}return dummyPoint.next;}
}

19.删除链表的倒数第N个节点

参考文章
题目连接

思路

个人题解

class Solution {public ListNode removeNthFromEnd(ListNode head, int n) {ListNode dummyPoint = new ListNode();dummyPoint.next = head;ListNode slowPoint = dummyPoint;ListNode fastPoint = dummyPoint;for (int i = 0; i < n + 1; i++) {fastPoint = fastPoint.next;}while (fastPoint != null) {slowPoint = slowPoint.next;fastPoint = fastPoint.next;}slowPoint.next = slowPoint.next.next;return dummyPoint.next;}
}

面试题 02.07. 链表相交

参考文章
题目连接

思路

个人题解

public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if (headA == null || headB == null) {return null;}ListNode A = headA;ListNode B = headB;int aLen = 0 , bLen = 0;while (A.next != null) {aLen++;A = A.next;}while (B.next != null) {bLen++;B = B.next;}A = headA;B = headB;int difLen = Math.abs(aLen - bLen);if (aLen > bLen) {for (int i = 0; i < difLen; i++) {A = A.next;}}else {for (int i = 0; i < difLen; i++) {B = B.next;}}while (A != null) {if (A == B) {return A;}A = A.next;B = B.next;}return null;}
}

面试题 02.07. 链表相交

参考文章
题目连接

思路

个人题解

public class Solution {public ListNode detectCycle(ListNode head) {if (head == null) {return null;}ListNode fastPoint = head;ListNode slowPoint = head;while (fastPoint != null && fastPoint.next != null) {slowPoint = slowPoint.next;fastPoint = fastPoint.next.next;if (fastPoint == slowPoint) {fastPoint = head;while(fastPoint != slowPoint){fastPoint = fastPoint.next;slowPoint = slowPoint.next;}return fastPoint;}}return null;}
}

更多推荐

代码随想录算法训练营第四天

本文发布于:2024-02-06 02:40:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1745676.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   训练营   第四天   代码   随想录

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!