美文网首页
【教3妹学算法】2道链表类题目

【教3妹学算法】2道链表类题目

作者: 程序员小2 | 来源:发表于2022-09-24 14:51 被阅读0次
    3妹

    题目1:反转链表

    给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

    示例 1:


    image.png

    输入:head = [1,2,3,4,5]
    输出:[5,4,3,2,1]
    示例 2:


    image.png

    输入:head = [1,2]
    输出:[2,1]
    示例 3:

    输入:head = []
    输出:[]

    提示:

    链表中节点的数目范围是 [0, 5000]
    -5000 <= Node.val <= 5000

    java代码1:

    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
         public ListNode reverseList(ListNode head) {
                if (head == null || head.next == null) {
                    return head;
                }
    
                ListNode pre = null;
                ListNode temp = head;
                ListNode reverseHead = null;
                while (temp != null) {
                    ListNode next = temp.next;
                    if (next == null) {
                        reverseHead = temp;
                    }
    
                    temp.next = pre;
                    pre = temp;
                    temp = next;
                }
    
                return reverseHead;
            }
    }
    

    题目2:环形链表

    给你一个链表的头节点 head ,判断链表中是否有环。

    如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

    如果链表中存在环 ,则返回 true 。 否则,返回 false 。

    示例 1:

    image.png

    输入:head = [3,2,0,-4], pos = 1
    输出:true
    解释:链表中有一个环,其尾部连接到第二个节点。
    示例 2:

    输入:head = [1,2], pos = 0
    输出:true
    解释:链表中有一个环,其尾部连接到第一个节点。
    示例 3:

    输入:head = [1], pos = -1
    输出:false
    解释:链表中没有环。

    提示:

    链表中节点的数目范围是 [0, 104]
    -105 <= Node.val <= 105
    pos 为 -1 或者链表中的一个 有效索引 。

    java代码2:

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public boolean hasCycle(ListNode head) {
            if(head == null || head.next == null) {
                return false;
            }
    
            ListNode slow = head;
            ListNode fast = head.next;
    
            while(fast != null && fast.next != null) {
                if(slow == fast) {
                    return true;
                }
                slow = slow.next;
                fast = fast.next.next;
            }
    
            return false;
        }
    }
    

    相关文章

      网友评论

          本文标题:【教3妹学算法】2道链表类题目

          本文链接:https://www.haomeiwen.com/subject/uonoortx.html