链表常见算法实现(一)

LeetCode 206. 反转链表

/* 实现单链表的反转 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    ListNode* reverseList(ListNode* head) {
    
    
        if (head == nullptr || head->next == nullptr) {
    
    
            return head;
        }
        ListNode* pre = nullptr;
        ListNode* cur = head;
        ListNode* next = nullptr;
        while (cur != nullptr) {
    
    
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

LeetCode 237. 删除链表中的节点

/* 这道题看似简单,实际上有一个非常重要的限制条件,就是给定的节点不是最后一个节点 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    void deleteNode(ListNode* node) {
    
    
        node->val = node->next->val;
        node->next = node->next->next;
    }
};

如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢

猜你喜欢

转载自blog.csdn.net/xiao_ma_nong_last/article/details/105115493