Chapter 05 Compound Data Type - Constructed Type
4. Application - Linked List
Linked List is a linear data structure, whose implementation is a structure type containing a pointer whose base type is itself as its member. The data is stored in the structure type’s other members.
struct Node {
int data;
Node *next;
};
- Create a Linked List by Inserting Nodes into the Head
const int N = 10;
Node* InsCreate(){
Node* head = NULL;
for (int i = 0; i < N; i++){
Node* p = new Node;
p->data = i; //cin >> p->data; is also Okay.
p->next = head;
head = p;
}
return head;
}
Notice that
InsCreate
creates a linked list with a reversed order contrary to your input order.If you want the regular order, try the following method.
- Create a Linked List by Inserting Nodes into the Tail
const int N = 10;
Node* AppCreate(){
Node* head = NULL,* tail = NULL;
for (int i = 0; i < N; ++i){
Node* p = new Node;
p->data = i; // cin >> p->data;
p->next = NULL;
if (head = NULL)
head = p;
else
tail->next = p;
tail = p;
}
return head;
}
- Output of a Linked List - Travel of the Linked List
void PrintList(Node* head) {
if (!head)
cout << "List is empty. \n";
else {
while (head) {
cout << head->data << " ";
head = head->next;
}
cout << endl;
}
}
- Insert a Node into a Linked List
void InsertNode (Node* head, int i) {
Node* current = head;
int j = 1;
while (j < i && current->next != NULL) {
current = current->next;
++j;
}
if (j == i) {
Node* p = new Node;
cin >> p->data;
p->next = current->next;
current->next = p;
}
else
cout << "There's no ith node. \n";
}
- Delete a Node of a Linked List
Node* DeleteNode(Node* head, int i) {
if (i == 1) {
Node* current = head;
head = head->next;
delete current;
}
else {
Node* previous = head;
int j = 1;
while (j < i - 1 && previous->next != NULL) {
previous = previous->next;
++j;
}
if (previous->next != NULL) {
Node* current = previous->next;
previous->next = current->next;
delete current;
}
else
cout << "There's no ith node. \n";
}
return head;
}
- Delete the Whole List
void DeleteList(Node* head) {
while (head) {
Node* current = head;
head = head->next;
delete current;
}
}
- Insertion Sort
Node* Insert(Node* h, Node* p) {
if(p->data < h->data) {
p->next = h;
h = p;
return h;
}
Node* cur = h;
Node* prev;
while (cur) {
if(p->data < cur->data)
break;
prev = cur;
cur = cur->next;
}
p->next = prev->next;
prev->next = p;
return h;
}
Node* InsSort(Node* head) {
if (head == NULL || head->next == NULL)
return head;
Node* cur = head->next;
head->next = NULL;
while (cur) {
Node* prev = cur;
cur = cur->next;
head = Insert(head, prev);
}
return head;
}
When dealing with problems concerning linked lists, pay attention to the following conditions:
- an empty linked list.
- a linked list with only one node.
- manipulating the first node
- manipulating the last node
- Next of the last node is NULL.
- The pointer manipulating the linked list has pointed to the last element.
And we must reserve a head pointer because the linked list is single-directional.