【代码随想录】19.删除链表的倒数第 N 个结点、160.相交链表、142.环形链表 II

19.删除链表的倒数第 N 个结点、160.相交链表、142.环形链表 II

19.删除链表的倒数第 N 个结点-Medium

快慢指针实现

状态:已完成

// 19.删除链表的倒数第 N 个结点
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* dummyHead = new ListNode(0);
        dummyHead->next;
        ListNode* fast = dummyHead;
        ListNode* slow = dummyHead;
        while(n-- && fast->next != NULL){
        	fast = fast->next;
        }
        fast = fast->next;
        while(fast != NULL){
        	slow = slow->next;
        	fast = fast->next;
        }
        slow->next = slow->next->next;
        return dummyHead->next;
    }
};

160.相交链表-Easy

状态:已完成

代码随想录题解:

// 160.相交链表
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    	ListNode* curA = headA;
    	ListNode* curB = headB;
    	int lenA = 0, lenB = 0; // A、B 链表长度
    	// 计算 A 链表长度
    	while(curA != NULL){
    		curA = curA->next;
    		lenA++;
    	}
    	// 计算 B 链表长度
    	while(curB != NULL){
    		curB = curB->next;
    		lenB++;
    	}
    	// curA 和 curB 回到各自链表起点
    	curA = headA;
    	curB = headB;
    	// 比较链表长度,让A链表最长
    	if(lenB > lenA){
    		swap(lenA, lenB);
    		swap(curA, curB);
    	}
    	// 计算链表长度差
    	int gap = lenA - lenB;
    	// 对齐末尾位置,保证 A、B 链表最后一位对齐
    	while(gap--){
    		curA = curA->next;
    	}
    	while(curA != NULL){
    		if(curA == curB){ // 找到相交结点
    			return curA; // 返回相交结点位置
    		}
    		curA = curA->next; // A链表按位往后走
    		curB = curB->next; // B链表按位往后走
    	}
    	return NULL; // 不相交返回NULL
    }
};

142.环形链表 II-Medium

状态:已完成

代码随想录题解:

// 142.环形链表 II
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode* fast = head;
        ListNode* slow = head;
        while(fast != NULL && fast->next != NULL){
            slow = slow->next;
            fast = fast->next->next;
            if(fast == slow){
                ListNode* index1 = fast;
                ListNode* index2 = head;
                while(index1 != index2){
                    index1 = index1->next;
                    index2 = index2->next;
                }
                return index2;
            }
        }
        return NULL;
    }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值