几道简单的链表题

复习一下链表,做几个简单的题目

链表是否有环

class Solution {
    
    
public:
    bool hasCycle(ListNode *head) {
    
    
        ListNode *slow = head;
        ListNode *quick = head;
        if(quick == NULL || quick->next==NULL || quick->next->next==NULL){
    
    
            return false;
        }
        quick = quick ->next ->next;
        slow = slow->next;
        while(slow!=quick){
    
    
            if(quick->next==NULL || quick->next->next==NULL){
    
    
                return false;
            }else{
    
    
                slow = slow->next;
                quick=quick->next->next;
            }
        }
        return true;
    }
};

两个链表是否有公共结点,返回第一个公共结点

在这里插入代码片class Solution {
    
    
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    
    
        ListNode *A =headA;
        ListNode *B =headB;
        int lengthA=0;
        while(headA!=NULL){
    
    
            lengthA++;
            headA = headA->next;
        }
        int lengthB=0;
        while(headB!=NULL){
    
    
            lengthB++;
            headB = headB->next;
        }
        while(lengthB>lengthA){
    
    
            lengthA++;
            B = B->next;
        }
        while(lengthB<lengthA){
    
    
            lengthB++;
            A = A->next;
        }
        while(A!=B){
    
    
            A = A->next;
            B = B->next;
            if(A==NULL){
    
    
                return NULL;
            }
        }
        return A;
    }
};

找到链表倒数N个结点

class Solution {
    
    
public:
    ListNode* getKthFromEnd(ListNode* head, int k) {
    
    
        ListNode* pre = head;
        ListNode* post = head;
        int count = 0;
        while(count<k){
    
    
            post = post->next;
            count++;
        }
        while(post!=NULL){
    
    
            post = post->next;
            pre = pre ->next;
        }
        return pre;
    }
};

反转链表,头插法

class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        ListNode* current = head;
        ListNode* pre = NULL;
        while(current){
    
    
            ListNode* post = current->next;
            current->next = pre;
            pre = current;
            current = post;
        }
        return pre;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_38616018/article/details/114481528