Showing posts with label linked list. Show all posts
Showing posts with label linked list. Show all posts

Friday, October 30, 2015

Leetcode: Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.
Subscribe to see which companies asked this question
--------------------------------------------
--------------------------------------------
It only gives you the access to a node in a list. So it's impossible to delete the node itself as we don't know the previous node! Instead of delete the node, a compensation method is to copy the value of next to this node and delete the next node. 
///////////////////////////////////////////////////
//code
class Solution {
public:
    void deleteNode(ListNode* node) {
        ListNode *p=node->next;
        node->val=node->next->val;
        node->next=p->next;
        delete p;
    }
};


Leetcode: Intersection 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.

-----------------------------------------
----------------------------------------
1. find the length of two lists: lenA , lenB,
(after 1, we can check whether a connection exist or not by checking the final nodes of the two lists are the same or not. If not, return directly!)
2. using two pointers pa, pb. Move the pointer forward along the longer list by abs(lenA-lenB) nodes. 
3. then move both pointers ahead step by step and check whether there is a intersection. 
NOTE 1:
 a case below:
when only one node exist and is also the intersection:
pa->[1]<-pb
NOTE 2:
when pa->NULL,
           pb->NULL,
then we have   pa==pb???. The answer is yes!!
////////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
              //check input
              if (headA == NULL || headB == NULL)return NULL;
              //find the length of two list
              ListNode *pa = headA, *pb = headB;
              int countA = 0, countB = 0;
              while (pa != NULL){
                     pa = pa->next;
                     countA++;
              }
              while (pb != NULL){
                     pb = pb->next;
                     countB++;
              }
              //check there are intersection or not
              if (pa != pb)return NULL;
              //move pointer forward by abs(countA-countB)
              pa = headA;
              pb = headB;
              if (countA>countB){
                     for (int i = 0; i<countA - countB; i++){
                           pa = pa->next;
                     }
              }
              else{
                     for (int i = 0; i<countB - countA; i++){
                           pb = pb->next;
                     }
              }
              //FIND THE INTERSECTION NODE
              while (pa!= NULL){
                     if (pa == pb)return pa;
                     else{
                           pa = pa->next;
                           pb = pb->next;
                     }
              }
       }
};



Thursday, October 29, 2015

Leetcode: Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?

-----------------------------------------------------------------
-----------------------------------------------------------------
An interesting problem. 
Using two pointers: slow and fast. fast proceeds two nodes/step while slow one node/step. They will meet eventually if there is a loop inside. 
/////////////////////////////////////////////////////////////
//codes
class Solution {
public:
       bool hasCycle(ListNode *head) {
              //check input
              if (head == NULL || head->next == NULL)return false;
              //loop
              ListNode *slow = head, *fast = head;
              while (fast != NULL && fast->next != NULL){
                     fast = fast->next->next;
                     slow = slow->next;
                     if (fast == NULL)return false;
                     else if (fast == slow)return true;
              }
              return false;
       }
};

Leetcode: Merge Two Sorted Lists

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.
------------------------------------------
-----------------------------------------
Just merge two sorted lists into one sorted list. Nothing special. 
/////////////////////////////////////////////////
//codes
class Solution {
public:
       ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
              //check input
              if (l1 == NULL)return l2;
              if (l2 == NULL)return l1;
              //dummy node
              ListNode*dum = new ListNode(-1), *pl1 = l1, *pl2 = l2, *p = dum;
              while (pl1 != NULL && pl2 != NULL){
                     if (pl1->val<pl2->val){
                           p->next = pl1;
                           p = p->next;
                           pl1 = pl1->next;
                     }
                     else{
                           p->next = pl2;
                           p = p->next;
                           pl2 = pl2->next;
                     }
              }
              //check left nodes and connect to p
              if (pl1 != NULL)p->next = pl1;
              else p->next = pl2;

              p = dum->next;
              delete dum;
              return p;
       }
};

Wednesday, October 28, 2015

Leetcode: Palindrome Linked List

Given a singly linked list, determine if it is a palindrome.
Follow up:
Could you do it in O(n) time and O(1) space?

---------------------------------------------
--------------------------------------------
1. find the middle node first, note that
    1   2   3   4 
    1   2   3   4   5
    the middle node for above cases are 2 and 3, respectively. Using two pointers method to find the middle node:
              ListNode *mid = head, *last = head;
              //locate the mid node
              while (last != NULL && last->next != NULL){
                     last = last->next->next;
                     if (last != NULL)mid = mid->next;
              }
2. reverse all the nodes after the middle node. Check here for how to reverse all nodes!
3. check the palindrome with two pointers both in forward direction. 

///////////////////////////////////////////////
//code
class Solution {
public:
       bool isPalindrome(ListNode* head) {
              //check input
              if (head == NULL || head->next == NULL)return true;
              ListNode *mid = head, *last = head;
              //locate the mid node
              while (last != NULL && last->next != NULL){
                     last = last->next->next;
                     if (last != NULL)mid = mid->next;
              }
              //reverse all nodes after mid node
              ListNode *cur = mid->next, *pre = cur->next;
              cur->next = NULL;
              while (pre != NULL){
                     ListNode *tmp = pre->next;
                     pre->next = cur;
                     cur = pre;
                     pre = tmp;
              }
              mid->next = cur;
              //CHECK with two pointers, both forward
              mid = mid->next;
              last = head;
              while (mid != NULL){
                     if (last->val != mid->val)return false;
                     else {
                           last = last->next;
                           mid = mid->next;
                     }
              }
              return true;
       }
};