Algorithm and data structure
  • Algorithm and data structure
  • Break Away: Programming And Coding Interviews & Cracking coding interview
    • System design and scalability
    • Performance and Complexity
    • Big O Notation
    • Sorting trade-off
    • Selection sort
    • Bubble sort
    • Insertion sort
    • Shell sort
    • Merge sort
    • Quick sort
    • Binary search
    • Recursion
    • Binary tree
    • Breadth First Traversal
    • Depth First Pre-Order
    • Binary search tree
    • Stack
    • Queue
    • Linked list
    • Doubly linked list
    • String
    • Pointer and array
    • Bit manipulation
    • General programming problems
    • Priority queue
    • Balanced binary search tree
    • Binary heap
    • Heap sort
    • Graphs
    • Topological sort
  • Leetcode
    • 1. Two Sum
    • 2. Add Two Numbers
    • 3. Longest Substring Without Repeating Characters
    • 4. Median of Two Sorted Arrays
    • 5. Longest Palindromic Substring
    • 6.ZigZag Conversion
    • 7. Reverse Integer
    • 8. String to Integer (atoi)
    • 9. Palindrome Number
    • 11. Container With Most Water
    • 12. Integer to Roman
    • 13. Roman to Integer
    • 14. Longest Common Prefix
    • 15. 3Sum
    • 16. 3Sum Closest
    • 17. Letter Combinations of a Phone Number
    • 18. 4Sum
    • 19. Remove Nth Node From End of List
    • 20. Valid Parentheses
    • 21. Merge Two Sorted Lists
    • 22. Generate Parentheses
    • 23. Merge k Sorted Lists
    • 24. Swap Nodes in Pairs
    • 25. Reverse Nodes in k-Group
    • 26. Remove Duplicates from Sorted Array
    • 27. Remove Element
    • 28. Implement strStr()
    • 29. Divide Two Integers
    • 30. Substring with Concatenation of All Words
    • 31. Next Permutation
    • 32. Longest Valid Parentheses
    • 33. Search in Rotated Sorted Array
    • 34. Find First and Last Position of Element in Sorted Array
    • 35. Search Insert Position (Easy)
    • 36. Valid Sudoku
    • 37. Sudoku Solver
    • 38. Count and Say
    • 39. Combination Sum
    • 40. Combination Sum II
    • 41. First Missing Positive
    • 43. Multiply Strings
    • 45. Jump Game II
    • 46. Permutations (Medium)
    • 47. Permutations II (Medium)
    • 48. Rotate Image
    • 49. Group Anagrams
    • 50. Pow(x, n)
    • 51. N-Queens
    • 52. N-Queens II
    • 53. Maximum Subarray
    • 54. Spiral Matrix
    • 55. Jump Game
    • 56. Merge Intervals
    • 57. Insert Interval
    • 58. Length of Last Word
    • 59. Spiral Matrix II
    • 61. Rotate List
    • 62. Unique Paths
    • 63. Unique Paths II
    • 64. Minimum Path Sum
    • 66. Plus One
    • 67. Add Binary
    • 69. Sqrt(x)
    • 70. Climbing Stairs
    • 73. Set Matrix Zeroes
    • 74. Search a 2D Matrix
    • 75. Sort Colors
    • 76. Minimum Window Substring
    • 77. Combinations
    • 78. Subsets
    • 79. Word Search
    • 80. Remove Duplicates from Sorted Array II
    • 81. Search in Rotated Sorted Array II
    • 82. Remove Duplicates from Sorted List II
    • 83. Remove Duplicates from Sorted List
    • 84. Largest Rectangle in Histogram
    • 86. Partition List
    • 88. Merge Sorted Array
    • 89. Gray Code
    • 90. Subsets II
    • 92. Reverse Linked List II
    • 94. Binary Tree Inorder Traversal (Medium)
    • 95. Unique Binary Search Trees II
    • 96. Unique Binary Search Trees
    • 98. Validate Binary Search Tree
    • 100. Same Tree (Easy)
    • 101. Symmetric Tree
    • 102. Binary Tree Level Order Traversal
    • 103. Binary Tree Zigzag Level Order Traversal
    • 104. Maximum Depth of Binary Tree
    • 105. Construct Binary Tree from Preorder and Inorder Traversal
    • 106. Construct Binary Tree from Inorder and Postorder Traversal
    • 107. Binary Tree Level Order Traversal II (Easy)
    • 108. Convert Sorted Array to Binary Search Tree
    • 109. Convert Sorted List to Binary Search Tree
    • 110. Balanced Binary Tree
    • 111. Minimum Depth of Binary Tree
    • 112. Path Sum
    • 113. Path Sum II
    • 114. Flatten Binary Tree to Linked List
    • 116. Populating Next Right Pointers in Each Node
    • 117. Populating Next Right Pointers in Each Node IIㄟˋ大
    • 118. Pascal's Triangle
    • 119. Pascal's Triangle II
    • 120. Triangle
    • 121. Best Time to Buy and Sell Stock
    • 122. Best Time to Buy and Sell Stock II
    • 123. Best Time to Buy and Sell Stock III
    • 125. Valid Palindrome
    • 654. Maximum Binary Tree
    • 127. Word Ladder
    • 129. Sum Root to Leaf Numbers
    • 130. Surrounded Regions (Medium)
    • 131. Palindrome Partitioning
    • 133. Clone Graph
    • 134. Gas Station
    • 136. Single Number
    • 137. Single Number II
    • 138. Copy List with Random Pointer
    • 139. Word Break
    • 141. Linked List Cycle
    • 143. Reorder List
    • 144. Binary Tree Preorder Traversal
    • 145. Binary Tree Postorder Traversal
    • 147. Insertion Sort List
    • 148. Sort List
    • 151. Reverse Words in a String
    • 152. Maximum Product Subarray
    • 153. Find Minimum in Rotated Sorted Array
    • 154. Find Minimum in Rotated Sorted Array II
    • 155. Min Stack
    • 160. Intersection of Two Linked Lists
    • 164. Maximum Gap
    • 169. Majority Element (Easy)
    • 173. Binary Search Tree Iterator
    • 174. Dungeon Game (Hard)
    • 189. Rotate Array
    • 198. House Robber (Easy)
    • 199. Binary Tree Right Side View (Medium)
    • 203. Remove Linked List Elements
    • 206. Reverse Linked List
    • 213. House Robber II (Medium)
    • 215. Kth Largest Element in an Array (Medium)
    • 222. Count Complete Tree Nodes
    • 226. Invert Binary Tree
    • 230. Kth Smallest Element in a BST
    • 232. Implement Queue using Stacks
    • 234. Palindrome Linked List (Easy)
    • 235. Lowest Common Ancestor of a Binary Search Tree
    • 236. Lowest Common Ancestor of a Binary Tree
    • 237. Delete Node in a Linked List
    • 240. Search a 2D Matrix II
    • 242. Valid Anagram
    • 257. Binary Tree Paths
    • 283. Move Zeroes
    • 337. House Robber III (Medium)
    • 347. Top K Frequent Elements
    • 349. Intersection of Two Arrays
    • 409. Longest Palindrome (Easy)
    • 437. Path Sum III
    • 442. Find All Duplicates in an Array
    • 449. Serialize and Deserialize BST
    • 450. Delete Node in a BST
    • 543. Diameter of Binary Tree
    • 572. Subtree of Another Tree
    • 653. Two Sum IV - Input is a BST
    • 654. Maximum Binary Tree
    • 700. Search in a Binary Search Tree
    • 701. Insert into a Binary Search Tree
    • 783. Minimum Distance Between BST Nodes
    • 876.Middle of the Linked List
    • 942. DI String Match
  • Notes of algorithms
    • Binary Tree traversal
    • 廣度優先搜尋 (Breadth-first Search)
    • Divide and Conquer
    • Linked list: Insert Node
    • Dynamic programming
    • 深度優先搜尋 (Depth-first Search)
    • Lowest Common Ancestor (LCA)
    • Asymptotic notation
    • Binary search tree
    • AVL Tree (Height Balanced BST)
    • Linked list: Split the list
    • Linked list: Traverse the list
    • Linked list: Delete node
    • Heap sort
    • Cartesian tree
  • C++
Powered by GitBook
On this page
  • 1.Traverse
  • 2.Get the length of a linked list
  • 3.Get the Nth element in a linked list
  • 4.Pop the first element in the linked list
  • 5.Delete all the elements in the linked list
  • 6.Insert an element at the Nth
  • 7.Insert an element at the right position in a sorted list
  • 8.Append one list to the end of another
  • 9.Append a new element to the end of a linked list
  • 10.Front back split
  • 11.Remove duplicates in a sorted list
  • 12. Sorted merge
  • 13.Move node from the head of one list and add to the front of another
  • 14.Reverse
  1. Break Away: Programming And Coding Interviews & Cracking coding interview

Linked list

1.Traverse

struct node* h = head;
while (h != null)
{
    h = h->next;
}

2.Get the length of a linked list

int getLength(struct node* head)
{
    int length = 0;
    while (head != null)
    {
        length++;
        head = head->next;
    }
    return length;
}

3.Get the Nth element in a linked list

struct node* getNth(struct node* head, int n)
{
    if (n < 0)
    {
        return NULL;
    }
    int length = 0;
    while (head != null && length < n)
    {
        length++;
        head = head->next;
    }
    return head;
}

4.Pop the first element in the linked list

int pop(struct node** headRef)
{
    assert(headRef != NULL);
    if (*headRef == NULL)
    {
        struct node* next = (*headRef)->next;
        int data = (*headRef)->data;
        free(*headRef);
        
        *headRef = next;
        return data;
    }

    assert(0);
}

5.Delete all the elements in the linked list

void deleteList(struct node** headRef)
{
    assert(headRef != NULL);
    struct node* head = *headRef;
    struct node* next = NULL;
    while (head == NULL)
    {
        next = head->next;
        head->next = NULL;
        free(head);
        
        head = next;
        return data;
    }
}

6.Insert an element at the Nth

void inserNth(struct node** headRef, int data, int n)
{
    assert(headRef != NULL);
    assert(n >= 0);
    
    //插入頭部
    if (n== 0 || *headRef == NULL)
    {
        struct node* headNode = create_node(data);
        headNode->next = *headRef;
        *headRef = headNode;
        return;
    }
    
    int index = 0;
    struct node* head = *headRef;
    struct node* prev = *headRef;
    
    //插入中間
    while (head == NULL && index < n)
    {
        prev = head;
        head = head -> next;
        index++;
    }
    
    if (prev != NULL)
    {
        prev->next = create_node(data); 
        prev->next->next = head;
    }
}

7.Insert an element at the right position in a sorted list

void sortedInsert(struct node** headRef, int data)
{
    assert(headRef != NULL);
    struct node* head = *headRef;
    struct node* prev = *NULL;
    
    while (head == NULL && data > head->data)
    {
        prev = head;
        head = head -> next;
    }
    
    struct node* newNode = create_node(data);
    
    if (prev != NULL)
    {
        //插入中間
        prev->next = newNode;
    }
    else
    {
        //插入頭部
        *headRef = newNode;
    }
    
    newNode->next = head;
}

8.Append one list to the end of another

void append_second_list(struct node** list_a, struct node** list_b)
{
    assert(list_a != NULL && list_b != NULL);
    
    //插入頭部
    if (*list_a == NULL)
    {
        *list_a = *list_b;
        *list_b = NULL;
        return;
    }
    
    //插入尾部
    struct node* head = *list_a;
    while (head->next != NULL)
    {
        head = head->next;
    }
    head->next=>next = *list_b;
    *list_b = NULL;
}

9.Append a new element to the end of a linked list

void append_data(struct node** headRef, int data)
{
    assert(headRef != NULL);
    //插入頭部
    if (*headRef == NULL)
    {
        *headRef = (struct node*)malloc(sizeof(struct node));
        (*headRef)->data = data;
        (**headRef)->next = NULL;
        return;
    }
    
    //插入尾部
    struct node* head = *headRef;
    while (head->next != NULL)
    {
        head = head->next;
    }
    head->next = (struct node*)malloc(sizeof(struct node));
    head->next->data = data;
    head->next=>next = NULL;
}

10.Front back split

void front_back_split(struct node** source,
                      struct node** frontRef,
                      struct node** backRef)
{
    assert(frontRef != NULL && backRef != NULL);
    if (source == NULL)
    {
        *frontRef == NULL;
        *backRef == NULL;
        return;
    }
    
    if (source->next == NULL)
    {
        *frontRef == source;
        *backRef == NULL;
        return;
    }
    
    struct node* slow = source;
    struct node* fast = source;
    while (fast != NULL)
    {
        fast = fast->next;
        if (fast == NULL)
        {
            break;
        }
        fast = fast->next;
        if (fast != NULL)
        {
            slow = slow->next;
        }
    }
    *frontRef = source;
    *backRef = slow->next;
    slow->next = NULL;
}

11.Remove duplicates in a sorted list

void remove_duplicates(struct node** source)
{
    if (source == NULL)
    {
        return;
    }
    
    struct node* curr = source->next;
    struct node* prev = source;
    
    while (curr != NULL)
    {
        if (curr != NULL && curr->data == prev->data)
        {
            prev->next = curr->next;
            curr->next = NULL;
            free(curr);
            
            curr = prev->net;
            continue;
        }
        prev = curr;
        curr = curr -> next;
    }
}

12. Sorted merge

struct node* sorted_merge(struct node** a, struct node** b)
{
    if (a == NULL)
    {
        return b;
    }
    else if (b == NULL)
    {
        return a;
    } 
    
    struct node* head;
    if (a->data < b->data)
    {
        head = a;
        a = a->next;
    }
    else
    {
        head = b;
        b = b->next;
    } 
    
    struct node* curr = head;
    
    while (a != NULL & b != NULL)
    {
        if (a->data < b->data)
        {
            curr->next = a;
            a = a->next;
        }
        else
        {
            curr->next = b;
            b = b->next;
        }
        curr = curr->next;
    }
    if (a != NULL)
    {
        curr->next = a;
    }
    else
    {
        curr->next = b;
    }
    
    return head;
}

13.Move node from the head of one list and add to the front of another

void move_node(struct node** sourceRef, struct node** destRef)
{
    assert(sourceRef != NULL && destRef != NULL);
    if (*sourceRef == NULL)
    {
        return;
    }
    
    struct node* node_to_move = *sourceRef;
    *sourceRef = (*sourceRef)->next;
    node_to_move->next = *destRef;
    *destRef = node_to_move;
}

14.Reverse

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if (head == NULL)
        {
            return NULL;
        }
        
        ListNode *prev = head;
        ListNode *curr = head->next;
        prev->next = NULL;
        
        while (curr != NULL)
        {
            ListNode *next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
};
PreviousQueueNextDoubly linked list

Last updated 6 years ago