Linked List - 92. 109. 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

提示:for循环找根结点,leftend -> next = NULL,递归

答案:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* sortedListToBST(ListNode* head) {
        if(head == nullptr)
            return NULL;
        ListNode* p1=head;
        ListNode* p2=head;
        ListNode* leftend=nullptr;
        int length=0;
        while(p1!=nullptr)
        {
            length++;
            p1=p1->next;
        }
        if(length==1)
        {
            TreeNode* root=new TreeNode(head->val);
            return root;
        }
        for(int i=0;i<(length/2);++i)
        {
            if(i==length/2-1)
                leftend=p2;
            p2=p2->next;
        }
        leftend->next=nullptr;
        TreeNode* root=new TreeNode(p2->val);
        //TreeNode* output=&root;
        root->left=sortedListToBST(head);
        root->right=sortedListToBST(p2->next);
        
        return root;
        
    }
};

141Linked List Cycle

 

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) {
        ListNode *slow = head;
        ListNode *fast = head;
        while(fast != NULL && fast -> next != NULL){
            slow = slow -> next;
            fast = fast -> next -> next;
            if(slow == fast)  return true;
        }
        return false;
    }
};

142Linked List Cycle II

 

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.

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

提示:

2 Sslow = Sfast
2 * ( x + m*c + a ) = (x + n *c + a)
从而可以推导出:
x = (n - 2 * m )*c - a
= (n - 2 *m -1 )*c + c - a
即环前面的路程 = 数个环的长度(为可能为0) + c - a

答案:

/**
 * 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;
        ListNode *fast  = head;
        ListNode *entry = head;
    
        while (fast->next && fast->next->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {                      // there is a cycle
                while(slow != entry) {               // found the entry location
                    slow  = slow->next;
                    entry = entry->next;
                }
                return entry;
            }
        }
        return NULL;                                 // there has no cycle
    }
};

143Reorder List

 

提示:方法一:把链表平分,反转第二部分,合并

           方法二: vector<ListNode*> v; 保存链表结点。  start++    end--

答案:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head || !head->next) return;
    
        // find the middle node: O(n)
        ListNode *p1 = head, *p2 = head->next;
        while (p2 && p2->next) {
            p1 = p1->next;
            p2 = p2->next->next;
        }

        // cut from the middle and reverse the second half: O(n)
        ListNode *head2 = p1->next;
        p1->next = NULL;

        p2 = head2->next;
        head2->next = NULL;
        while (p2) {
            p1 = p2->next;
            p2->next = head2;
            head2 = p2;
            p2 = p1;
        }

        // merge two lists: O(n)
        for (p1 = head, p2 = head2; p2; ) {
          auto t = p1->next;
          p1->next = p2;
          p2 = p2->next;
          p1 = p1->next->next = t;
        }
    }
};

 

class Solution {
public:
    void reorderList(ListNode* head) {
        if (!head)
            return;
        ListNode* p = head;
        vector<ListNode*> v;
        while(p) {
            v.push_back(p);
            p = p->next;
        }
        int i = 0, j = v.size() - 1;
        while (i < j) {
            v[i]->next = v[j];
            i++;
            if (i == j)
                break;
            v[j]->next = v[i];
            j--;
        }
        v[i]->next = NULL;
        return;
    }
};

 

147. Insertion Sort List  

 

 

Sort a linked list using insertion sort.


A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list.
With each iteration one element (red) is removed from the input data and inserted in-place into the sorted list
 

Algorithm of Insertion Sort:

  1. Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list.
  2. At each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there.
  3. It repeats until no input elements remain.


Example 1:

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

提示:pre指向插入位置的前一个结点,cur遍历链表。插入后,pre指向dummy。

答案:

ListNode* insertionSortList(ListNode* head) {
        ListNode dummy = ListNode(0);
        dummy.next = head;
        ListNode *pre = &dummy;
        ListNode *cur = head;
        while(cur){
            if (cur -> next && cur -> next -> val < cur -> val) {
                 while (pre -> next && pre -> next -> val < cur -> next -> val)
                    pre = pre -> next;
                /* Insert cur -> next after pre.*/
                ListNode *temp = pre -> next;
                pre -> next = cur -> next;
                cur -> next = cur -> next -> next;
                pre -> next -> next = temp;
                pre = &dummy;
            }else{
                cur = cur -> next;
            }  
        }
        return dummy.next;
    }

148. Sort List

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

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

提示:首先龟兔算法把链表一分为二,然后合并

答案:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* sortList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode *slow = head;
        ListNode *fast = head->next;
        while(fast && fast->next)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        fast = slow->next;
        slow->next = NULL;
        return merge(sortList(head),sortList(fast));
    }
    ListNode* merge(ListNode *l1, ListNode *l2){
        ListNode dummy(INT_MIN);
        ListNode *node = &dummy;
        while(l1 && l2)
        {
            if(l1->val <= l2->val)
            {
                node->next = l1;
                l1 = l1->next;
            }
            else
            {
                node->next = l2;
                l2 = l2->next;
            }
            node = node->next;
        }
        node->next = l1 ? l1 : l2;
        return dummy.next;
    }
};

160Intersection of Two Linked Lists

 


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.

 

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

提示:相当于L1+L2与L2+L1比较,两者长度相等,并且从所求点开始重合。

答案:

/**
 * 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) {
        ListNode *ptrA = headA, *ptrB = headB;
        while (ptrA != ptrB) { 
            ptrA = ptrA ? ptrA->next : headB;
            ptrB = ptrB ? ptrB->next : headA;
        }
        return ptrA;
    }
};

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值