链表集合题目

leetcode 83

leetcode 83

链表题目很多解决办法都是有两种解决办法。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* node = head;
        while(node != nullptr && node->next != nullptr){
            if(node->val == node->next->val){
                node->next = node->next->next;
            }else{
                node = node->next;
            }
        }
        return head;
    }
};

以下为递归解决办法

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if(head ==nullptr || head->next == nullptr){
            return head;
        }
        head->next = deleteDuplicates(head->next);
        if(head->val == head->next->val){
            head = head->next;
        }
        return head;
    }
};

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 == NULL || head->next ==NULL) return head;
        ListNode* node;
        node = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        return node;
    }
};

栈方法:

/**
 * 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) { 
        stack s;
        while(head != NULL){
            s.push(head);
            head = head->next;
        } 
        ListNode* resHead = new ListNode(0);
        ListNode* cur = resHead;
        while(!s.empty()){
            cur->next = (ListNode*)s.top();
            s.pop();
            cur = cur->next;
        }
        cur->next = NULL;
        return resHead->next;
    }
};

你可能感兴趣的:(链表集合题目)