链表相关习题

链表问题难道在于临界点的处理,主要考察coding能力

注意:一般while循环里的条件,cur->next->next如果想要程序正常运行,就必须满足cur和cur->next都不是空指针,但是cur->next->next可以是空指针,因为没有对他进行使用。

206. 反转链表 - 力扣(LeetCode)

//双指针法
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode*cur = head, *pre = nullptr, *tmp = nullptr;
        while (cur) {
            tmp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
};

24. 两两交换链表中的节点 - 力扣(LeetCode)

思路:cur结点后面两个数进行交换,如果后面不够就直接返回

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode *dummyHead = new ListNode(0, head);
        ListNode *cur = dummyHead;
        while (cur->next && cur->next->next) {
            ListNode *node1 = cur->next;
            ListNode *node2 = cur->next->next;
            ListNode *node3 = cur->next->next->next;//记录下一个节点后需要换位的结
            cur->next = node2;
            node1->next = node3;
            node2->next = node1;
            cur = node1;
        }  
        return dummyHead->next; 
    }
};

92. 反转链表 II - 力扣(LeetCode)

class Solution {
public:
    ListNode* reverse(ListNode *head) {
        ListNode *cur = head;
        ListNode *pre = nullptr;
        ListNode *next = nullptr;
        while (cur) {//当cur为nullptr时,就不需要和前者有联系了,因为前者就是头结点啊。
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        ListNode *pre = nullptr;
        ListNode *rightnode = nullptr;
        ListNode *leftnode = nullptr;
        ListNode *dummyHead = new ListNode(0, head);
        ListNode *tmp = dummyHead;//暂时保存头结点
        ListNode *end = nullptr;
        for (int i = 0; i<left-1; i++) {//找到left左边的一个节点
            tmp = tmp->next;
        }
        pre = tmp;
        leftnode = pre->next;
        for (int i = 0; i<right - left +1; i++) {
            tmp = tmp->next;
        }
        rightnode = tmp;
        end = rightnode->next;
        //切断连接
​
        rightnode->next = nullptr;
        rightnode = reverse(leftnode);
​
        pre->next = rightnode;
        leftnode->next = end;
        return dummyHead->next;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值