链表的练习题

本文介绍了链表的六个经典操作题目,包括删除等于给定值的节点、反转链表、找到链表的中心节点、找到链表中倒数第k个节点、合并两个有序链表以及链表分割。每个操作都提供了思路解析和相关代码实现。

1.  删除链表中等于给定值 val 的所有节点

力扣

思路:

 代码:

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        if (head == null) {
            return null;
        }
        ListNode prev = head;
        ListNode cur = head.next;
        while (cur != null) {
            if (cur.val == val) {
                prev.next = cur.next;
                cur = cur.next;
            }else {
                prev = cur;
                cur = cur.next;
            }
        }
        if (head.val == val) {
            head = head.next;
        }
        return head;
    }
}

2. 反转一个单链表

https://leetcode-cn.com/problems/reverse-linked-list/description/

思路:

     我们像定义一个空节点 prev,用来存储我们每次反转之后的结点, 然后定义一个 cur 结点用来遍历我们的链表,我们发现,在遍历 的过程中 我们反转后的 cur 结点会找不到下一个结点的位置,所以我们可以在找一个对象 curNext 来确定下一次 cur的位置。直至 cur 走完我们的链表,我们的头结点此时就是 prev,此时,反转链表完

以下是一些C++链表练习题及对应代码示例: 1. **反转链表**:将一个单链表反转。 ```cpp /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *cur = head, *pre = nullptr, *next = nullptr; while(cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } }; ``` 此代码通过迭代的方式,依次改变链表节点的指向,实现链表反转 [^1]。 2. **反转链表(另一种实现)**: ```cpp struct ListNode { int val; struct ListNode *next; }; typedef struct ListNode LN; struct ListNode* reverseList(struct ListNode* head) { if (head==NULL) return head; LN *n1, *n2, *n3; n1 = NULL; n2 = head; n3 = head->next; while(n2) { n2->next = n1; n1 = n2; n2 = n3; if(n3) n3 = n3->next; } return n1; } ``` 同样是反转链表的功能,采用不同的变量命名和逻辑流程 [^2]。 3. **查找两个链表的交点**:找出两个单链表相交的起始节点。 ```cpp struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) { struct ListNode *cur1 = headA; struct ListNode *cur2 = headB; int countA = 0, countB = 0; while(cur1) { ++countA; cur1 = cur1->next; } while(cur2) { ++countB; cur2 = cur2->next; } //此时的count就记录了两个链表的长度 cur1 = headA; cur2 = headB; int gap = abs(countA - countB); if(countA < countB) //B链更长,应该B先走差距步,让俩个链表起始位置一样 { while(gap--) { cur2 = cur2->next; } } else { while(gap--) { cur1 = cur1->next; } } //走到这两个链表就是一样长 //假设两个链表相交那么走会在末尾之前找到一个节点,两个val一样 while(cur1) { if(cur1 == cur2) { return cur2; } else { cur1 = cur1->next; cur2 = cur2->next; } } return NULL; } ``` 该代码先计算两个链表的长度,然后让长链表的指针先走长度差的步数,最后同时移动两个指针,找到相交节点 [^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值