LeetCode LinkedList 总结

All solutions below were implemented in C++

19 Remove Nth Node From End of List

https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:

Given n will always be valid.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if (!head->next) {
            return NULL;
        }
        ListNode *pre = head, *cur = head;
        for (int i = 0; i < n; i++) cur = cur->next;
        if (!cur) { // 移除第一个元素
            return head->next;
        }
        while (cur->next) {
            cur = cur->next;
            pre = pre->next;
        }
        pre->next = pre->next->next;
        return head;
    }
};

23 Merge k Sorted Lists

https://leetcode.com/problems/merge-k-sorted-lists/description/

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    struct Node {
        bool operator() (ListNode *x, ListNode *y) { return x->val > y->val; }
    };

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if (lists.size() == 0) return NULL;
        if (lists.size() == 1) return lists[0];
        priority_queue<ListNode*, vector<ListNode*>, Node> q;

        ListNode *blank = (ListNode*) new ListNode(0), *pre = blank;

        for (int i = 0; i < lists.size(); i++) {
            if (lists[i] != NULL) {
                q.push(lists[i]);
            }
        }

        while (!q.empty()) {
            pre->next = q.top();
            pre = pre->next;
            q.pop();
            if (pre != NULL && pre->next != NULL) {
                q.push(pre->next);
            }
        }

        return blank->next;

    }
};

61 Rotate List

https://leetcode.com/problems/rotate-list/description/

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if (head == NULL || head->next == NULL) { return head; }
        int len = 0;
        ListNode *p = head, *pre, *tail;
        while (p != NULL) {
            len++;
            pre = p;
            p = p->next;
        }
        k = len - k % len;
        if (k == len) { return head; }
        tail = pre;
        tail->next = head;
        p = head;
        for (int i = 0; i < k; i++) {
            pre = p;
            p = p->next;
        }
        head = p;
        pre->next = NULL;
        return head;
    }
};

82 Remove Duplicates from Sorted List II

https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

Example 1:

Input: 1->2->3->3->4->4->5
Output: 1->2->5
Example 2:

Input: 1->1->1->2->3
Output: 2->3

/**
 * 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 == NULL || head->next == NULL) { return head; }
        ListNode *p = head, *blank, *pre;
        blank = (ListNode*) new ListNode(0);
        blank->next = head;
        pre = blank;
        while (p != NULL && p->next != NULL) {
            while (p->next != NULL && p->val == p->next->val) {
                p = p->next;
            }
            if (p != pre->next) {
                p = p->next;
                pre->next = p;
            } else {
                pre = p;
                p = p->next;
            }
        }
        return head = blank->next;
    }
};

83 Remove Duplicate from Sorted List

https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/

Given a sorted linked list, delete all duplicates such that each element appear only once.

Example 1:

Input: 1->1->2
Output: 1->2
Example 2:

Input: 1->1->2->3->3
Output: 1->2->3

/**
 * 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 *p, *q;
        p = head, q= head;
        while (p != NULL) {
            do {
                q = q->next;
                if (q == NULL) break;
            } while (p->val == q->val);
            p->next = q;
            p = q;
        }
        return head;
    }
};

86 Partition List

https://leetcode.com/problems/partition-list/description/

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* partition(ListNode* head, int x) {
        if (head == NULL) { return head; }
        ListNode *less = (ListNode*) new ListNode(INT_MIN);
        ListNode *more = (ListNode*) new ListNode(INT_MAX);
        less->next = NULL, more->next = NULL;
        ListNode *p = less, *q = more;
        while (head != NULL) {
            if (head->val < x) {
                less->next = head;
                less = less->next;
            } else {
                more->next = head;
                more = more->next;
            }
            head = head->next;
        }
        less->next = q->next;
        more->next = NULL;
        return p->next;
    }
};

92 Reverse Linked List II

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

Reverse a linked list from position m to n. Do it in one-pass.

Note: 1 ≤ m ≤ n ≤ length of list.

Example:

Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int m, int n) {
        if (head == NULL || m == n) { return head; }
        ListNode *blank = (ListNode *) new ListNode(0);
        blank->next = head;
        ListNode *pre = blank;
        ListNode *left = head, *right = head;
        for (int i = 1; i < m; i++) {
            pre = left;
            left = left->next;
        }
        for (int i = 1; i < n; i++) {
            right = right->next;
        }
        while (left != right) {
            pre->next = left->next;
            left->next = right->next;
            right->next = left;
            left = pre->next;
        }
        return blank->next;
    }
};

142 Linked List Cycle II

https://leetcode.com/problems/linked-list-cycle-ii/description/

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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

        slow = head;
        while (slow != fast) {
            slow = slow->next;
            fast = fast->next;
        }

        return fast;
    }
};

203 Remove Linked List Elements

https://leetcode.com/problems/remove-linked-list-elements/description/

Remove all elements from a linked list of integers that have value val.

Example:

Input: 1->2->6->3->4->5->6, val = 6
Output: 1->2->3->4->5

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeElements(ListNode* head, int val) {
        ListNode *blank = new ListNode(0);
        blank->next = head;
        ListNode *p = blank, *q = p->next;
        while (q != NULL) {
            if (q->val == val) {
                p->next = q->next;
                q = q->next;
            } else {
                q = q->next;
                p = p->next;
            }
        }
        return blank->next;
    }
};

Palindrome Linked List

https://leetcode.com/problems/palindrome-linked-list/description/

Given a singly linked list, determine if it is a palindrome.

Example 1:

Input: 1->2
Output: false
Example 2:

Input: 1->2->2->1
Output: true
Follow up:
Could you do it in O(n) time and O(1) space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool isPalindrome(ListNode* head) {
        vector<int> values;
        ListNode *p = head;
        while (p != NULL) {
            values.push_back(p->val);
            p = p->next;
        }
        return isPalindrome4vector(values);
    }

    bool isPalindrome4vector(vector<int> s) {
        int p = 0, q = s.size() - 1;
        while (p < q) {
            if (s[p] == s[q]) {
                p = p + 1;
                q = q - 1;
            } else {
                return false;
            }
        }
        return true;
    }
};

Intersection of Two Linked Lists

https://leetcode.com/problems/intersection-of-two-linked-lists/description/

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if (headA == NULL || headB == NULL) { return NULL; }
        ListNode *a = headA, *b = headB;
        while (a != b) {
            a = a == NULL ? headB : a->next;
            b = b == NULL ? headA : b->next;
        }
        return a;
    }
};

141 Linked List Cycle

https://leetcode.com/problems/linked-list-cycle/description/

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (head == NULL) { return false; }
        ListNode *fast = head, *slow = head;
        while (fast != NULL && fast->next != NULL) {
            fast = fast->next->next;
            slow = slow->next;
            if (slow == fast) { return true; }
        }
        return false;
    }
};

21 Merge Two Sorted Lists

https://leetcode.com/problems/merge-two-sorted-lists/description/

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
#define null NULL
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* l;
        ListNode *p = l1, *q = l2;
        if (l1 == null && l2 == null)
            return null;
        else if (l1 != null && l2 == null)
            l = l1;
        else if (l1 == null && l2 != null)
            l = l2;
        else
            l = (l1->val <= l2->val) ? l1 : l2;
        ListNode *r = l;
        if (p == l) {
            p = p->next;
        } else {
            q = q->next;
        }
        while (p != null && q != null) {
            if (p->val <= q->val) {
                r->next = p;
                p = p->next;
                r = r->next;
            } else {
                r->next = q;
                q = q->next;
                r = r->next;
            }
        }
        if (p != null) {
            r->next = p;
        }
        if (q != null) {
            r->next = q;
        }
        return l;
    }
};

2 Add Two Numbers

https://leetcode.com/problems/add-two-numbers/description/

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#define null NULL
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    int carry = 0;
    struct ListNode* l3 = (struct ListNode*) malloc(sizeof(struct ListNode));
    struct ListNode* cur = l3;
    int e1 = 0;
    int e2 = 0;
    int sum = 0;
    while(l1 != null || l2 != null) {
        struct ListNode* temp = (struct ListNode*) malloc(sizeof(struct ListNode));
        e1 = (l1 == null) ? 0 : l1->val;
        e2 = (l2 == null) ? 0 : l2->val;
        sum = e1 + e2 + carry;
        temp->val = sum % 10;
        carry = sum / 10;
        cur->next = temp;
        cur = temp;
        if (l1 != null)
            l1 = l1->next;
        if (l2 != null)
            l2 = l2->next;
    }
    if (carry != 0) {
        cur->next = (struct ListNode*) malloc(sizeof(struct ListNode));
        cur->next->val = carry;
        cur = cur->next;
    }
    cur->next = null;
    return l3->next;
}

206 Reverse Linked List

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

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

/**
 * 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 *pre = head, *p = head;
        while (p != NULL) {
            ListNode *tmp = p->next;
            if (pre == head) {
                pre->next = NULL;
            }
            p->next = pre;
            pre = p;
            p = tmp;
        }
        return pre;
    }
};

237 Delete Node in a Linked List

https://leetcode.com/problems/delete-node-in-a-linked-list/description/

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Given linked list – head = [4,5,1,9], which looks like following:

4 -> 5 -> 1 -> 9

Example 1:

Input: head = [4,5,1,9], node = 5
Output: [4,1,9]
Explanation: You are given the second node with value 5, the linked list
should become 4 -> 1 -> 9 after calling your function.
Example 2:

Input: head = [4,5,1,9], node = 1
Output: [4,5,9]
Explanation: You are given the third node with value 1, the linked list
should become 4 -> 5 -> 9 after calling your function.
Note:

The linked list will have at least two elements.
All of the nodes’ values will be unique.
The given node will not be the tail and it will always be a valid node of the linked list.
Do not return anything from your function.

/**
 * 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) {
        ListNode *pre = node, *p = node->next;
        while (p != NULL) {
            pre->val = p->val;
            if (p->next == NULL) {
                pre->next = NULL;
                break;
            }
            pre = p;
            p = p->next;
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值