Linked List - 92. 109. 138. 141. 142. 143. 147. 148. 160.(138在HashTable已做)

92Reverse Linked List II

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

提示:pre为第m-1个结点,通过结点指针move = last -> next,使得move指向的结点移动到pre后,cur指向的结点即为反转后的第n个结点。

答案:

/**
 * 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) {
        ListNode dummy = ListNode(0);
        dummy.next = head;
        ListNode *pre = &dummy;
        for(int i = 0; i < m - 1; i++) pre = pre -> next;
        ListNode *cur = pre -> next;
        for(int i = 0; i < n - m; i++){
            ListNode *move = cur -> next;
            cur -> next = move -> next;
            move -> next = pre -> next;
            pre -> next = move;
        }
        return dummy.next;
    }
};

109Convert Sorted List to Binary Search Tree

提示:

答案:


138Copy List with Random Pointer

提示:

答案:


141Linked List Cycle

提示:

答案:


142Linked List Cycle II

提示:

答案:


143Reorder List

提示:

答案:


147. Insertion Sort List  

提示:

答案:


148. Sort List

提示:

答案:


160Intersection of Two Linked Lists

提示:

答案:


猜你喜欢

转载自blog.csdn.net/qq_27012963/article/details/80264825
今日推荐