链表相关

2021/12/28 23:12:12

本文主要是介绍链表相关,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、链表反转

模板:

1.1 反转链表

 1 class Solution {
 2     public ListNode reverseList(ListNode head) {
 3         ListNode prev = null;
 4         ListNode curr = head;
 5         while (curr != null) {
 6             ListNode next = curr.next;
 7             curr.next = prev;
 8             prev = curr;
 9             curr = next;
10         }
11         return prev;
12     }
13 }

 

1.2 反转某个区间(leff, right)的节点

K 个一组翻转链表

反转链表 II

 1 public ListNode[] myReverse(ListNode head, ListNode tail) {
 2     ListNode prev = tail.next;
 3     ListNode p = head;
 4     while (prev != tail) {
 5         ListNode nex = p.next;
 6         p.next = prev;
 7         prev = p;
 8         p = nex;
 9     }
10     return new ListNode[]{tail, head};
11 }

 

 

2、快慢指针

比较两种方式 快指针的初始位置,以及循环条件

2.1 链表的中间结点

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        ListNode* slow = head;
        ListNode* fast = head;
        while (fast != NULL && fast->next != NULL) {
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

 

2.2 环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

 



这篇关于链表相关的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程