Topic: | Data Structures (Linked lists) |
---|---|
Author: | Peter Bui <pbui@cse.nd.edu> |
Date: | September 07, 2009 |
Linked List
A collection of elements where each element is composed of the data and a set of links to subsequent elements.
typedef struct IntNode {
struct IntNode *next;
int data;
} IntNode;
Singly-linked: Node only has links to next node:
[1]->[2]->[3]->[4]
Doubly-linked: Node has links to next and previous nodes:
[1]<=>[2]<=>[3]<=>[4]
Circularly-linked: List is a cycle with no head or tail:
[1]->[2]->[3]->[4] [1]<=>[2]<=>[3]<=>[4] ^--------------| ^=================^
Head: The first element in the list, usually must be tracked.
Tail: The last element in the list. Last link is normally NULL.
Use list for doubly-linked list and slist for singly-linked list.
list<int> mList;
mList.push_back(0);
mList.push_front(0);
Given a singly-linked list, return the Mth to the last element.
Input:
0 1 2 3 4 5 6 7 8 9 3 5
Output:
6 4
Complete find_mth_to_the_last example.
Given a linked list, determine if you have a cycle.
Acyclic:
[1]->[2]->[3]->[4]->[5]->0 # Ends with link to NULL
Cyclic:
[1]->[2]->[3]->[4]->[5] # Tail points to node in list ^---------|
bool is_cyclic(Node *head) { // From Programming Interviews Exposed
Node *fast, *slow;
fast = slow = head;
while (true) {
if (!fast || !fast->next) {
return false;
} else if (fast == slow || fast->next == slow) {
return true;
} else {
slow = slow->next;
fast = fast->next->next;
}
}
}