Vous êtes sur la page 1sur 47

12/26/2014

C++ Tutorial: Linked List - 2014

bogotobogo
QT5

ANDROID

ALGORITHMS

HOME

C++

ABOUT US

JAVA

PHP

PRODUCTS

DESIGN PATTERNS
STREAMING

OUR SERVICES

PYTHON

C#

CONTACT US

DEVOPS

FFMPEG

MATLAB

OPENCV

Search

K Hong
Follow
730 followers

C++ TUTORIAL - LINKED LIST


EXAMPLES - 2014

List of C++
Tutorials
C++ Home

Bogotobogo's contents
To see more items, click left or right arrow.

Algorithms &
Data Structures
in C++ ...
Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)
auto_ptr

I hope this site is informative and helpful.

Binary Tree
Example Code
Blackjack with
Qt
Boost shared_ptr,
weak_ptr, mpl,
lambda, etc.
Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...

C++ Example

Data Structure

C++ Source Code

Video Tutorial

Classes and
Structs
Constructor
C++11(C++0x):
http://www.bogotobogo.com/cplusplus/linkedlist.php

Bogotobogo Image / Video Processing


1/47

12/26/2014

C++ Tutorial: Linked List - 2014

rvalue
references,
move
constructor, and
lambda, etc.

Computer Vision & Machine Learning


with OpenCV, MATLAB, FFmpeg, and scikit-learn.

C++ API Testing


C++ Keywords const, volatile,
etc.
Debugging
Crash &
Memory Leak

I hope this site is informative and helpful.

Design Patterns
in C++ ...
Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III
- Eclipse CDT
Plugin for gcc
ARM Toolchain

LINKED LISTS
A linked list is a basic data structure where each item contains the information that we need
to get to the next item.
The main advantage of linked lists over arrays is that the links provide us with the capability to
rearrange the item efficiently. This flexibility is gained at the expense of quick access to any
arbitrary item in the list, because the only way to access to an item in the list is to follow links
from the beginning.

LINKED LIST EXAMPLES


The following examples are for the linked list. Inside each example, we have several
operations:
Reversing the linked list (#1, #3, #4)
Copying the linked list(#1)

Exceptions

Detecting circular (loop) linked list(#5)

Friend
Functions and
Friend Classes

Comparing the two linked list(#1)

fstream: input &


output

Adding, deleting, inserting, and searching a node (all examples)

Function
Overloading

Deleting the linked list(#1)

Stack implementation with linked list (#6, #7)


Finding intersection and union of two lists (#8)

Functors
(Function
Objects) I Introduction
Functors
(Function
Objects) II Converting
function to
functor
Functors
(Function
Objects) General
Git and GitHub
Express...
GTest (Google
http://www.bogotobogo.com/cplusplus/linkedlist.php

Example 1
When the head of the list is not a global pointer.
Example 2 and Example 3
When the head of the list is a global pointer.
There are some implementation differences between these two examples.
Example 4
Used class & structure in that class.
Example 5A
Detecting circular (loop) linked list.
Example 5B
2/47

12/26/2014

C++ Tutorial: Linked List - 2014

Unit Test) with


Visual Studio
2012

Detecting circular (loop) linked list (Generic Class with Template).


Example 6
Stack with linked list data structure.

Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)
Linked List
Basics
Linked List
Examples
make & CMake
make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.

Example 7
Class Stack with linked list data structure.
Example 7B
Class Stack with linked list data structure.

Multi-Threaded
Programming II Native Thread
for Win32 (A)

Example 7C
Class Stack using linked list with query for minimum value.
Example 7D
Stack Class Using Linked List with Query for Minimum Value (additional stack).

Multi-Threaded
Programming II Native Thread
for Win32 (B)

Example 8
Queue Struct with linked list data structure.

Multi-Threaded
Programming II Native Thread
for Win32 (C)

Example 8B
Queue Class with linked list data structure.
Example 9
Finding intersection and union of two linked lists.

Multi-Threaded
Programming II C++ Thread for
Win32
Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads
MultiThreading/Parallel
Programming IPC
Multi-Threaded
Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)
Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)
Multithread
Debugging

Example 10
Generic linked lists.
Also, there is another set of linked list quiz.

EXAMPLE 1
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
// only for the 1st Node
void initNode(struct Node *head,int n){
head->data = n;
head->next =NULL;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

3/47

12/26/2014

C++ Tutorial: Linked List - 2014

Object
Returning
Object Slicing
and Virtual
Table
OpenCV with
C++

// apending
void addNode(struct Node *head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = NULL;
Node *cur = head;
while(cur) {
if(cur->next == NULL) {
cur->next = newNode;
return;
}
cur = cur->next;
}

Operator
Overloading I
Operator
Overloading II self assignment
Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays
Preprocessor Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)

}
void insertFront(struct Node **head, int n) {
Node *newNode = new Node;
newNode->data = n;
newNode->next = *head;
*head = newNode;
}
struct Node *searchNode(struct Node *head, int n) {
Node *cur = head;
while(cur) {
if(cur->data == n) return cur;
cur = cur->next;
}
cout << "No Node " << n << " in list.\n";
}
bool deleteNode(struct Node **head, Node *ptrDel) {
Node *cur = *head;
if(ptrDel == *head) {
*head = cur->next;
delete ptrDel;
return true;
}
while(cur) {
if(cur->next == ptrDel) {
cur->next = ptrDel->next;
delete ptrDel;
return true;
}
cur = cur->next;
}
return false;

Stack Unwinding
Standard
Template
Library (STL) I Vector & List
Standard
Template
Library (STL) II Maps
Standard
Template
Library (STL) II unordered_map

}
/* reverse the list */
struct Node* reverse(struct Node** head)
{
Node *parent = *head;
Node *me = parent->next;
Node *child = me->next;

Standard
Template
Library (STL) II Sets
http://www.bogotobogo.com/cplusplus/linkedlist.php

/* make parent as tail */


parent->next = NULL;
while(child) {
4/47

12/26/2014

C++ Tutorial: Linked List - 2014

me->next = parent;
parent = me;
me = child;
child = child->next;

Standard
Template
Library (STL) III
- Iterators

}
me->next = parent;
*head = me;
return *head;

Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V
- Function
Objects
Static Variables
and Static Class
Members
String
String II sstream etc.
Taste of
Assembly
Templates
Template
Specialization
Template
Specialization Traits

}
/* Creating a copy of a linked list */
void copyLinkedList(struct Node *node, struct Node **pNew)
{
if(node != NULL) {
*pNew = new Node;
(*pNew)->data = node->data;
(*pNew)->next = NULL;
copyLinkedList(node->next, &((*pNew)->next));
}
}
/* Compare two linked list */
/* return value: same(1), different(0) */
int compareLinkedList(struct Node *node1, struct Node *node2)
{
static int flag;
/* both lists are NULL */
if(node1 == NULL && node2 == NULL) {
flag = 1;
}
else {
if(node1 == NULL || node2 == NULL)
flag = 0;
else if(node1->data != node2->data)
flag = 0;
else
compareLinkedList(node1->next, node2->next);
}

Template
Implementation
& Compiler (.h
or .cpp?)
The this Pointer
Type Cast
Operators
Upcasting and
Downcasting
Virtual
Destructor &
boost::shared_ptr
Virtual
Functions

Programming
Questions and
Solutions

Strings and
Arrays
Linked List
Recursion
Bit Manipulation
Small Programs
(string, memory
functions etc.)
Math &
Probability
Multithreading

return flag;
}
void deleteLinkedList(struct Node **node)
{
struct Node *tmpNode;
while(*node) {
tmpNode = *node;
*node = tmpNode->next;
delete tmpNode;
}
}
void display(struct Node *head) {
Node *list = head;
while(list) {
cout << list->data << " ";
list = list->next;
}
cout << endl;
cout << endl;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

5/47

12/26/2014

C++ Tutorial: Linked List - 2014

140 Questions
by Google

Qt 5
EXPRESS...

int main()
{
struct Node *newHead;
struct Node *head = new Node;
initNode(head,10);
display(head);

Win32 DLL ...

addNode(head,20);
display(head);
Articles On C++

addNode(head,30);
display(head);
What's new in
C++11...
C++11 Threads
EXPRESS...
OpenCV...

Linked List
C++ Programming
C++ Tutorial

addNode(head,35);
display(head);
addNode(head,40);
display(head);
insertFront(&head,5);
display(head);
int numDel = 5;
Node *ptrDelete = searchNode(head,numDel);
if(deleteNode(&head,ptrDelete))
cout << "Node "<< numDel << " deleted!\n";
display(head);
cout << "The list is reversed\n";
reverse(&head);
display(head);
cout << "The list is copied\n";
copyLinkedList(head,&newHead);
display(newHead);
cout << "Comparing the two lists...\n";
cout << "Are the two lists same?\n";
if(compareLinkedList(head,newHead))
cout << "Yes, they are same!\n";
else
cout << "No, they are different!\n";
cout << endl;
numDel = 35;
ptrDelete = searchNode(newHead,numDel);
if(deleteNode(&newHead,ptrDelete)) {
cout << "Node "<< numDel << " deleted!\n";
cout << "The new list after the delete is\n";
display(newHead);
}
cout << "Comparing the two lists again...\n";
cout << "Are the two lists same?\n";
if(compareLinkedList(head,newHead))
cout << "Yes, they are same!\n";
else
cout << "No, they are different!\n";
cout << endl;
cout << "Deleting the copied list\n";

http://www.bogotobogo.com/cplusplus/linkedlist.php

6/47

12/26/2014

C++ Tutorial: Linked List - 2014

deleteLinkedList(&newHead);
display(newHead);
return 0;
}

Output from the run:


10
10 20
10 20 30
10 20 30 35
10 20 30 35 40
5 10 20 30 35 40
Node 5 deleted!
10 20 30 35 40
The list is reversed
40 35 30 20 10
The list is copied
40 35 30 20 10
Comparing the two lists...
Are the two lists same?
Yes, they are same!
Node 35 deleted!
The new list after the delete is
40 30 20 10
Comparing the two lists again...
Are the two lists same?
No, they are different!
Deleting the copied list

EXAMPLE 2
#include <iostream>
using namespace std;
struct node {
int data;
struct node * next;
};
node *head = NULL;
// returning the pointer to the element
http://www.bogotobogo.com/cplusplus/linkedlist.php

7/47

12/26/2014

C++ Tutorial: Linked List - 2014

// whose data is less than or equal to input data


struct node *searchNode(int n) {
if(head == NULL) return head;
node *cur = head;
node *prev = head;
while(cur) {
if(cur->data == n) return cur;
if(cur->data > n) return prev;
prev = cur;
cur = cur->next;
}
}
// returning the pointer to the element
// whose data is equal to input data
struct node *searchNode2(int n) {
if(head == NULL) return head;
node *cur = head;
node *prev = head;
while(cur) {
if(cur->data == n) return cur;
prev = cur;
cur = cur->next;
}
return cur;
}

List of C++
Tutorials

void addNode(int n) {
node *newNode = new node;
newNode->data = n;
newNode->next = NULL;

C++ Home

if(head == NULL) {
head = newNode;
return;
}
node *cur = head;
while(cur) {
if(cur->next == NULL) {
cur->next = newNode;
return;
}
cur = cur->next;
}

Algorithms &
Data Structures
in C++ ...
Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)
auto_ptr
Binary Tree
Example Code
Blackjack with
Qt
Boost shared_ptr,
weak_ptr, mpl,
lambda, etc.
Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...
Classes and
Structs
Constructor
C++11(C++0x):
rvalue
references,
move

}
void insertNode(int n) {
node *ptr = searchNode(n);
node *newNode = new node;
newNode->data = n;
node *cur = head;
while(cur) {
if(cur == ptr ) {
newNode->next = cur->next;
cur->next = newNode;
return;
}
cur = cur->next;
}
}
void deleteNode(int n) {

http://www.bogotobogo.com/cplusplus/linkedlist.php

8/47

12/26/2014

C++ Tutorial: Linked List - 2014

constructor, and
lambda, etc.

node *ptr = searchNode(n);


if(ptr == NULL)
cout << "No node with data = " << n << endl;
if(ptr == head) {
head = ptr->next;
return;
}
node *cur = head;
node *prev = head;

C++ API Testing


C++ Keywords const, volatile,
etc.
Debugging
Crash &
Memory Leak
Design Patterns
in C++ ...

while(cur) {
if(cur == ptr) {
prev->next = cur->next;
return;
}
prev = cur;
cur = cur->next;
}

Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III
- Eclipse CDT
Plugin for gcc
ARM Toolchain
Exceptions
Friend
Functions and
Friend Classes
fstream: input &
output
Function
Overloading
Functors
(Function
Objects) I Introduction
Functors
(Function
Objects) II Converting
function to
functor
Functors
(Function
Objects) General
Git and GitHub
Express...
GTest (Google
Unit Test) with
Visual Studio
2012

}
void display() {
struct node *list = head;
while(list) {
cout << list->data <<" ";
list = list->next;
}
cout << endl;
}
int main()
{
addNode(10);
display();
addNode(20);
display();
addNode(40);
display();
addNode(50);
display();
insertNode(30);
display();
deleteNode(40);
display();
return 0;
}

EXAMPLE 3

// linked list example - using struct


#include <iostream>
#include <cstring>
using namespace std;
struct node * initNode( char *, int );
void displayNode( struct node * );

http://www.bogotobogo.com/cplusplus/linkedlist.php

9/47

12/26/2014

C++ Tutorial: Linked List - 2014

Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)
Linked List
Basics
Linked List
Examples
make & CMake
make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.

void displayList( struct node * );


void addNode( struct node * );
struct node * searchName( struct node *, char * );
void deleteNode( struct node * );
void insertNode( struct node * );
void deleteList( struct node * );
struct node {
char name[20];
int id;
struct node *next;
};
struct node *head = (struct node *) NULL;
struct node *tail = (struct node *) NULL;
// allocates memory for the node
// assign values to the member of the structure
struct node * initNode( char *name, int id )
{
struct node *ptr = new node;
// error? then just return
if( ptr == NULL )
return static_cast<struct node *>(NULL);
// assign it
// then return pointer to ne node
else {
strcpy( ptr->name, name );
ptr->id = id;
return ptr;
}

Multi-Threaded
Programming II Native Thread
for Win32 (A)
Multi-Threaded
Programming II Native Thread
for Win32 (B)
Multi-Threaded
Programming II Native Thread
for Win32 (C)
Multi-Threaded
Programming II C++ Thread for
Win32
Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads

}
// adding to the end of list
void addNode( struct node *newnode )
{
// if there is no node, put it to head
if( head == NULL ) {
head = newnode;
tail = newnode;
}

MultiThreading/Parallel
Programming IPC

// link in the new_node to the tail of the list


// then mark the next field as the end of the list
// adjust tail to point to the last node

Multi-Threaded
Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)

tail->next = newnode;
newnode->next = NULL;
tail = newnode;

Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)

}
void insertNode( struct node *newnode )
{
struct node *temp, *prev;

Multithread
Debugging
Object
Returning
http://www.bogotobogo.com/cplusplus/linkedlist.php

if( head == NULL ) {


head = newnode;
tail = newnode;
head->next = NULL;
return;
}

// if an empty list,
// set 'head' to it
// set end of list to NULL

10/47

12/26/2014

C++ Tutorial: Linked List - 2014

Object Slicing
and Virtual
Table

temp = head;

// start at beginning of list


// while currentname < newname
while( strcmp( temp->name, newnode->name) < 0 ) {
// to be inserted then
temp = temp->next;
// goto the next node in list
if( temp == NULL )
// don't go past end of list
break;
}
// set previous node before we inser
// first check to see if it's insert
if( temp == head ) {
// before the first node
newnode->next = head;
// link next field to original list
head = newnode;
// head adjusted to new node
}
else {
// it's not the first node
prev = head;
// start of the list,
while( prev->next != temp ) {
// will cycle to node before temp
prev = prev->next;
}
prev->next = newnode;
// insert node between prev and next
newnode->next = temp;
if( tail == prev )
// if the new node is inserted at th
tail = newnode;
// end of the list the adjust 'end'
}

OpenCV with
C++
Operator
Overloading I
Operator
Overloading II self assignment
Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays
Preprocessor Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)
Stack Unwinding
Standard
Template
Library (STL) I Vector & List
Standard
Template
Library (STL) II Maps

}
struct node * searchName( struct node *ptr, char *name )
{
while( strcmp( name, ptr->name ) != 0 ) {
ptr = ptr->next;
if( ptr == NULL )
break;
}
return ptr;
}
struct node* searchId(struct node* ptr, int id) {
while( id != ptr->id ) {
ptr = ptr->next;
if( ptr == NULL )
break;
}
return ptr;
}
void reverse() {
// we need at least two nodes for the reverse to have any effect
if(head == NULL || head->next == NULL) return;

Standard
Template
Library (STL) II unordered_map
Standard
Template
Library (STL) II Sets
Standard
Template
Library (STL) III
http://www.bogotobogo.com/cplusplus/linkedlist.php

// Starting 2nd list as 'me' and 'head' is now 'me->next'


// and 'head->next' is pointing to NULL
// So, the 3rd list is now 'child' of 'me'
node *parent = head;
node *me = head->next;
node *child = me->next;
// convert head to tail
parent->next = NULL;
while(child != NULL){
me->next = parent;
11/47

12/26/2014

C++ Tutorial: Linked List - 2014

- Iterators

parent = me;
me = child;
child = child->next;

Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V
- Function
Objects
Static Variables
and Static Class
Members
String
String II sstream etc.

}
// when me reached the tail
// me becomes head
head = me;
// the head is now pointing to the 2nd last node
head->next = parent;
}
void deleteNode( struct node *ptr )
{
struct node *temp, *prev;
temp = ptr;
// node to be deleted
prev = head; // start of the list, will cycle to node before temp

Taste of
Assembly

if( temp == prev ) {


head = head->next;
if( tail == temp )
tail = tail->next;
delete temp ;
}
else {
while( prev->next != temp ) {
prev = prev->next;
}
prev->next = temp->next;
if( tail == temp )
tail = prev;
delete temp;
}

Templates
Template
Specialization
Template
Specialization Traits
Template
Implementation
& Compiler (.h
or .cpp?)
The this Pointer
Type Cast
Operators
Upcasting and
Downcasting
Virtual
Destructor &
boost::shared_ptr

// deleting first node?


// moves head to next node
// is it end, only one node?
// adjust end as well
// free up space
// if not the first node, then
// move prev to the node before
// the one to be deleted
// link previous node to next
// if this was the end node,
// then reset the end pointer
// free up space

}
void deleteList( struct node *ptr )
{
struct node *temp;

Virtual
Functions

Programming
Questions and
Solutions

Strings and
Arrays
Linked List

if( head == NULL ) return;

// don't try to delete an empty list

if( ptr == head ) {


head = NULL;
tail = NULL;
}
else {
temp = head;
while( temp->next != ptr )
temp = temp->next;
tail = temp;
}

// if we are deleting the entire list


// then reset head and
// end to empty

while( ptr != NULL ) {


temp = ptr->next;
delete ptr;
ptr = temp;
}

// while there are still nodes to delete


// record address of next node
// free this node
// point to next node to be deleted

// if it's not the entire list, readjust


// locate previous node to ptr
// set end to node before ptr

Recursion
Bit Manipulation
Small Programs
(string, memory
functions etc.)
Math &
Probability

Multithreading
140 Questions
by Google

void displayNode( struct node *ptr ) {


cout << ptr->id << ": " << ptr->name << endl;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

12/47

12/26/2014

C++ Tutorial: Linked List - 2014

Qt 5
EXPRESS...

Win32 DLL ...

void displayList( struct node *ptr ) {


while( ptr != NULL )
{
displayNode( ptr );
ptr = ptr->next;
}
}

Articles On C++

What's new in
C++11...
C++11 Threads
EXPRESS...
OpenCV...

#include <iostream>
using namespace std;
int main()
{
char* name;
int id, ch = 1;
struct node *ptr;
// add
ptr = initNode( "s1", 1 );
addNode(ptr);
ptr = initNode( "s2", 2 );
addNode(ptr);
ptr = initNode( "s3", 3 );
addNode(ptr);
ptr = initNode( "s4", 4 );
addNode(ptr);
ptr = initNode( "s5", 5 );
addNode(ptr);
displayList(head);
// delete
name = "s2";
ptr = searchName(head, name );
if( ptr == NULL ) {
cout << "\nName: " << name << " not found" << endl;
}
else {
cout << "\nDeleting a node ... ";
displayNode(ptr);
deleteNode( ptr );
}
displayList(head);
// insert
name = "s2";
id = 2;
ptr = initNode( name, id );
insertNode( ptr );
cout << "\nInserting a node ... ";
displayNode(ptr);
displayList(head);
// reverse
cout << "\nReversing the list ... \n";
reverse();
displayList(head);
// delete
cout << "\nIn the end, deleting the list ... \n";

http://www.bogotobogo.com/cplusplus/linkedlist.php

13/47

12/26/2014

C++ Tutorial: Linked List - 2014

deleteList(head);
displayList(head);
return 0;
}

EXAMPLE 4
// linked list example - using struct inside a class
#include <iostream>
#include <string>
using namespace std;
class list
{
public:
struct node {
int id;
string name;
struct node *next;
} *head, *tail, *ptr;
list():head(NULL),tail(NULL){} // constructor
~list();
// destructor
struct list::node* searchName(struct list::node*, string);
struct list::node* searchId(struct list::node*, int);
struct list::node* initNode(string, int);
void reverse();
void addNode( struct list::node*);
void insertNode( struct list::node*);
void deleteNode( struct list::node*);
void deleteList( struct list::node*);
void displayList( struct list::node*)const ;
void displayNode( struct list::node*) const;
};
list::~list() {
node *current,*temp;
current = head;
temp = head;
while(current != NULL) {
current = current->next;
delete temp;
temp = current;
}
}
struct list::node* list::initNode(string s, int i) {
struct node *ptr = new node;
// error? then just return
if( ptr == NULL )
return static_cast<struct node *>(NULL);
// assign it
// then return pointer to ne node
else {
http://www.bogotobogo.com/cplusplus/linkedlist.php

14/47

12/26/2014

C++ Tutorial: Linked List - 2014

ptr->name = s ;
ptr->id = i;
return ptr;
}
}
// adding to the end of list
void list::addNode( struct node *newNode ) {
// if there is no node, put it to head
if( head == NULL ) {
head = newNode;
tail = newNode;
}
// link in the new_node to the tail of the list
// then mark the next field as the end of the list
// adjust tail to point to the last node
tail->next = newNode;
newNode->next = NULL;
tail = newNode;
}
void list::insertNode( struct node *newnode ) {
struct node *temp, *prev;
if( head == NULL ) {
head = newnode;
tail = newnode;
head->next = NULL;
return;
}

// if an empty list,
// set 'head' to it

temp = head;

// start at beginning of list


// while currentname < newname
// to be inserted then
// goto the next node in list
// don't go past end of list

while( temp->name < newnode->name) {


temp = temp->next;
if( temp == NULL )
break;
}

if( temp == head ) {


newnode->next = head;
head = newnode;
}
else {
prev = head;
while( prev->next != temp ) {
prev = prev->next;
}
prev->next = newnode;
newnode->next = temp;
if( tail == prev )
tail = newnode;
}

// set end of list to NULL

// set previous node before we inser


// first check to see if it's insert
// before the first node
// link next field to original list
// head adjusted to new node
// it's not the first node
// start of the list,
// will cycle to node before temp

// insert node between prev and next

// if the new node is inserted at th


// end of the list the adjust 'end'

}
struct list::node* list::searchName(struct node* ptr, string name) {
while( name != ptr->name ) {
ptr = ptr->next;
if( ptr == NULL )
http://www.bogotobogo.com/cplusplus/linkedlist.php

15/47

12/26/2014

C++ Tutorial: Linked List - 2014

break;
}
return ptr;
}

List of C++
Tutorials
C++ Home
Algorithms &
Data Structures
in C++ ...
Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)
auto_ptr

struct list::node* list::searchId(struct node* ptr, int id) {


while( id != ptr->id ) {
ptr = ptr->next;
if( ptr == NULL )
break;
}
return ptr;
}
void list::reverse() {
// we need at least two nodes for the reverse to have any effect
if(head == NULL || head->next == NULL) return;

Binary Tree
Example Code

// Starting 2nd list as 'me' and 'head' is now 'me->next'


// and 'head->next' is pointing to NULL
// So, the 3rd list is now 'child' of 'me'
node *parent = head;
node *me = head->next;
node *child = me->next;

Blackjack with
Qt
Boost shared_ptr,
weak_ptr, mpl,
lambda, etc.

// convert head to tail


head->next = NULL;

Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...

// reverse pointer direction


me->next = head;

Classes and
Structs

while(child != NULL){
me->next = parent;
parent = me;
me = child;
child = child->next;
}
// when me reached the tail
// me becomes head
head = me;
// the head is now pointing to the 2nd last node
head->next = parent;

Constructor
C++11(C++0x):
rvalue
references,
move
constructor, and
lambda, etc.
C++ API Testing
C++ Keywords const, volatile,
etc.
Debugging
Crash &
Memory Leak
Design Patterns
in C++ ...

void list::deleteNode( struct list::node *ptr )


{
struct node *temp, *prev;
temp = ptr;
// node to be deleted
prev = head; // start of the list, will cycle to node before temp

Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II http://www.bogotobogo.com/cplusplus/linkedlist.php

if( temp == prev ) {


head = head->next;
if( tail == temp )
tail = tail->next;
delete temp ;
}
else {
while( prev->next != temp ) {
prev = prev->next;
}
prev->next = temp->next;

// deleting first node?


// moves head to next node
// is it end, only one node?
// adjust end as well
// free up space
// if not the first node, then
// move prev to the node before
// the one to be deleted
// link previous node to next
16/47

12/26/2014

C++ Tutorial: Linked List - 2014

gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III
- Eclipse CDT
Plugin for gcc
ARM Toolchain

if( tail == temp )


tail = prev;
delete temp;
}
}
void list::deleteList( struct node *ptr )
{
struct node *temp;

Exceptions
Friend
Functions and
Friend Classes
fstream: input &
output
Function
Overloading
Functors
(Function
Objects) I Introduction
Functors
(Function
Objects) II Converting
function to
functor
Functors
(Function
Objects) General
Git and GitHub
Express...
GTest (Google
Unit Test) with
Visual Studio
2012
Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)
Linked List
Basics
Linked List
Examples

// if this was the end node,


// then reset the end pointer
// free up space

if( head == NULL ) return;

// don't try to delete an empty list

if( ptr == head ) {


head = NULL;
tail = NULL;
}
else {
temp = head;
while( temp->next != ptr )
temp = temp->next;
tail = temp;
}

// if we are deleting the entire list


// then reset head and
// end to empty

while( ptr != NULL ) {


temp = ptr->next;
delete ptr;
ptr = temp;
}

// whilst there are still nodes to delet


// record address of next node
// free this node
// point to next node to be deleted

// if it's not the entire list, readjust


// locate previous node to ptr
// set end to node before ptr

}
void list::displayNode( struct list::node *ptr ) const
{
cout << ptr->id << ": " << ptr->name << endl;
}
void list::displayList( struct list::node *ptr ) const
{
if(!ptr) cout << "Nothing to display" << endl;
while(ptr) {
displayNode(ptr);
ptr = ptr->next;
}
}
int main()
{
int id;
string name;
list myList;
list::node* ptr;

make & CMake


make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.
Multi-Threaded
http://www.bogotobogo.com/cplusplus/linkedlist.php

// add
ptr = myList.initNode( "s1", 1 );
myList.addNode(ptr);
ptr = myList.initNode( "s2", 2 );
myList.addNode(ptr);
ptr = myList.initNode( "s3", 3 );
myList.addNode(ptr);
ptr = myList.initNode( "s4", 4 );
myList.addNode(ptr);
ptr = myList.initNode( "s5", 5 );
myList.addNode(ptr);
17/47

12/26/2014

C++ Tutorial: Linked List - 2014

Programming II Native Thread


for Win32 (A)

myList.displayList(myList.head);
// delete
name = "s2";
ptr = myList.searchName( myList.head, name );
if( ptr == NULL ) {
cout << "\nName: " << name << " not found" << endl;
}
else {
cout << "\nDeleting a node ... ";
myList.displayNode(ptr);
myList.deleteNode( ptr );
}
myList.displayList(myList.head);

Multi-Threaded
Programming II Native Thread
for Win32 (B)
Multi-Threaded
Programming II Native Thread
for Win32 (C)
Multi-Threaded
Programming II C++ Thread for
Win32
Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads

// insert
name = "s2";
id = 2;
ptr = myList.initNode( name, id );
myList.insertNode( ptr );
cout << "\nInserting a node ... ";
myList.displayNode(ptr);
myList.displayList(myList.head);

MultiThreading/Parallel
Programming IPC
Multi-Threaded
Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)

// reverse
cout << "\nReversing the list ... \n";
myList.reverse();
myList.displayList(myList.head);

Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)
Multithread
Debugging

// delete
cout << "\nIn the end, deleting the list ... \n";
myList.deleteList(myList.head);
myList.displayList(myList.head);
return 0;
}

Object
Returning
Object Slicing
and Virtual
Table
OpenCV with
C++
Operator
Overloading I
Operator
Overloading II self assignment
Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays

EXAMPLE 5A - DETECTING CIRCULAR (LOOP) LINKED LIST


/* This code has the following */
/*
1. Adding Nodes
2. Function returning the size of the list
3. Making the list circular (loop)
4. Detecting circular list
5. Recursive printing
*/
#include <iostream>
using namespace std;
struct Node
{
int data;
Node * next;
};
Node *root = 0;

Preprocessor http://www.bogotobogo.com/cplusplus/linkedlist.php

18/47

12/26/2014

C++ Tutorial: Linked List - 2014

Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)
Stack Unwinding
Standard
Template
Library (STL) I Vector & List
Standard
Template
Library (STL) II Maps
Standard
Template
Library (STL) II unordered_map
Standard
Template
Library (STL) II Sets
Standard
Template
Library (STL) III
- Iterators
Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V
- Function
Objects
Static Variables
and Static Class
Members

void addNode(int n)
{
if(root==0) {
root = new Node;
root->data = n;
root->next = 0;
return;
}
Node *cur = root;
while(cur) {
if(cur->next == 0) {
Node *ptr = new Node;
ptr -> data = n;
ptr -> next = 0;
cur -> next = ptr;
return;
}
cur = cur->next;
}
}
void makeCircular()
{
if(!root || !root->next) return;
Node *cur = root;
while(cur) {
if(cur->next == 0) {
cur->next = root;
return;
}
cur = cur->next;
}
}
int sizeOfList()
{
Node *cur = root;
int size = 0;
while(cur) {
size++;
if(cur->next == 0) {
return size;
}
cur = cur->next;
}
return size;
}
bool detectCircular()
{
// Assuming the list may not be circular

String
String II sstream etc.
Taste of
Assembly
Templates
Template
Specialization
Template
http://www.bogotobogo.com/cplusplus/linkedlist.php

if(!root || !root->next) return false;


Node *ptr1 = root;
Node *ptr2 = root;
while(ptr1 && ptr2) {
ptr1 = ptr1->next;
ptr2 = ptr2->next;
if(ptr2) {
ptr2 = ptr2->next;
if(!ptr2) return false;
19/47

12/26/2014

C++ Tutorial: Linked List - 2014

Specialization Traits

}
else {

Template
Implementation
& Compiler (.h
or .cpp?)

return false;
}
cout << ptr1->data << "," << ptr2->data << endl;
if(ptr1==ptr2) {
return true;
}

The this Pointer


Type Cast
Operators

}
return false;

Upcasting and
Downcasting

Virtual
Destructor &
boost::shared_ptr

void printRecursive(Node *ptr)


{
if(!ptr) {
cout << endl;
return;
}
cout << ptr->data << " ";
printRecursive(ptr->next);
}

Virtual
Functions

Programming
Questions and
Solutions

Strings and
Arrays
Linked List

int main(int argc, char **argv)


{
addNode(10);addNode(20);addNode(30);addNode(40);addNode(50);
addNode(60);addNode(70);addNode(80);addNode(90);addNode(100);

Recursion

printRecursive(root);

Bit Manipulation

cout << "size of list = " << sizeOfList() << endl;

Small Programs
(string, memory
functions etc.)

makeCircular();

Math &
Probability

if(detectCircular()) cout <<"Circular\n";


else cout << "Normal\n";

Multithreading
140 Questions
by Google

Output from the run:


Qt 5
EXPRESS...

Win32 DLL ...

Articles On C++

What's new in
C++11...
C++11 Threads
EXPRESS...

10 20 30 40 50 60 70 80 90 100
size of list = 10
20,30
30,50
40,70
50,90
60,10
70,30
80,50
90,70
100,90
10,10
Circular

OpenCV...

EXAMPLE 5B - DETECTING CIRCULAR (LOOP) LINKED LIST (GENERIC CLASS WITH


TEMPLATE)
http://www.bogotobogo.com/cplusplus/linkedlist.php

20/47

12/26/2014

C++ Tutorial: Linked List - 2014

#include <iostream>
#include <string>
using namespace std;
template <class T>
class LinkedList
{
private:
struct node
{
T data;
node * next;
} *head;
public:
LinkedList();
~LinkedList();
void add(T d);
void remove(T d);
void clear();
void makeCircular();
bool isCircular();
void display(const char* s);
};
template <class T>
LinkedList<T>::LinkedList()
{
head = NULL;
}
template <class T>
LinkedList<T>::~LinkedList()
{
node *p, *q;
p = head;
if(p == NULL) return;
while(p) {
q = p->next;
delete p;
p = q;
}
}
template <class T>
void LinkedList<T>::add(T d)
{
node *p, *q;
if(head == NULL) {
head = new node;
head->data = d;
head->next = NULL;
return;
}
p = head;
while(p->next != NULL)
p = p->next;
q = new node;
q->data = d;
q->next = NULL;
http://www.bogotobogo.com/cplusplus/linkedlist.php

21/47

12/26/2014

C++ Tutorial: Linked List - 2014

p->next = q;
}
template <class T>
void LinkedList<T>::remove(T d)
{
node *p, *q;
if(head == NULL) return;
p = head;
while(p) {
if(p->data == d) {
q->next = p->next;
delete p;
return;
}
q = p;
p = p->next;
}
}
template <class T>
void LinkedList<T>::clear()
{
node *p, *q;
if(head == NULL) return;
p = head;
while(p) {
q = p->next;
delete p;
if(q != head) {
head = NULL;
return;
}
p = q;
}
}
template <class T>
void LinkedList<T>::makeCircular()
{
node *p;
if(head == NULL || head->next == NULL) return;
p = head;
while(p) {
if(p->next == NULL) {
p->next = head;
return;
}
p = p->next;
}
}
template <class T>
bool LinkedList<T>::isCircular()
{
node *p, *pp;
if(head == NULL || head->next == NULL) return false;
p = head;
pp = head;
while(pp) {
p = p->next;
if(pp->next == NULL) return false;
http://www.bogotobogo.com/cplusplus/linkedlist.php

22/47

12/26/2014

C++ Tutorial: Linked List - 2014

pp = (pp->next)->next;
if(p == pp) return true;
}
return false;
}
template <class T>
void LinkedList<T>::display(const char* s)
{
node *p;
if(head == NULL) return;
p = head;
while(p) {
if(s == "string")
cout << p->data << endl;
else
cout << p->data << ' ';
p = p->next;
if(p != NULL) {
if(p == head) return;
}
}
if(s == "integer") cout << endl;
}
int main()
{
LinkedList<string> sList;
sList.add("Wolfgang Amadeus Mozart");
sList.add("Franz Peter Schubert");
sList.add("Pyotr Ilyich Tchaikovsky");
sList.add("Clude-Achille Debussy");
sList.add("Camille Saint-Saens");
sList.display("string");
sList.clear();
LinkedList<int> iList;
iList.add(40);
iList.add(50);
iList.add(60);
iList.add(70);
iList.add(80);
iList.add(90);
iList.add(100);
iList.add(10);
iList.add(20);
iList.add(30);
iList.display("integer");

List of C++
Tutorials
C++ Home
Algorithms &
Data Structures
in C++ ...

/* link last element to the first */


iList.makeCircular();

Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)

if(iList.isCircular()) cout <<"This is circular list\n";


iList.display("integer");
iList.clear();
cout << "\ndisplay after clear()\n";
iList.display("integer");

auto_ptr
Binary Tree
Example Code
Blackjack with
Qt

return 0;
}

Boost http://www.bogotobogo.com/cplusplus/linkedlist.php

23/47

12/26/2014

C++ Tutorial: Linked List - 2014

shared_ptr,
weak_ptr, mpl,
lambda, etc.
Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...
Classes and
Structs
Constructor
C++11(C++0x):
rvalue
references,
move
constructor, and
lambda, etc.
C++ API Testing
C++ Keywords const, volatile,
etc.
Debugging
Crash &
Memory Leak
Design Patterns
in C++ ...
Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III
- Eclipse CDT
Plugin for gcc
ARM Toolchain
Exceptions
Friend
Functions and
Friend Classes
fstream: input &
output

Output from the run is:


Wolfgang Amadeus Mozart
Franz Peter Schubert
Pyotr Ilyich Tchaikovsky
Clude-Achille Debussy
Camille Saint-Saens
40 50 60 70 80 90 100 10 20 30
This is circular list
40 50 60 70 80 90 100 10 20 30
display after clear()

EXAMPLE 6 - STACK USING LINKED LIST


This stack is using linked list as its data structure.
/* Stack operations */
#include <iostream>
using namespace std;
typedef struct Element
{
void *data;
struct Element *next;
} Element;
bool push(Element **top, void *data)
{
Element *elem = new Element;
if(!elem) return false;
elem->data = data;
elem->next = *top;
*top = elem;
return true;
}
bool createStack(Element **top)
{
*top = NULL;
return true;
}
bool pop(Element **top, void **data )
{
Element *elem;
if( !(elem = *top) ) return false;

Function
Overloading
Functors
(Function
Objects) I Introduction

*data = elem->data;
*top = elem->next;
delete elem;
return true;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

24/47

12/26/2014

C++ Tutorial: Linked List - 2014

Functors
(Function
Objects) General

bool deleteStack(Element **top)


{
Element *elem;
while(*top) {
elem = (*top)->next;
delete *top;
*top = elem;
}
return true;

Git and GitHub


Express...

Functors
(Function
Objects) II Converting
function to
functor

GTest (Google
Unit Test) with
Visual Studio
2012
Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)
Linked List
Basics
Linked List
Examples
make & CMake
make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.

void printStack(Element *top)


{
if(top==NULL) {
cout << "Empty!" << endl;
}
Element *cur = top;
while(cur) {
cout << *(static_cast<int *>(cur->data)) << " ";
cur = cur->next;
}
cout << endl << endl;
}
int main()
{
Element *head;
createStack(&head);
int n1 = 10, n2 = 20, n3 = 30, n4 = 40, n5 = 50;
push(&head, &n1);
push(&head, &n2);
push(&head, &n3);
push(&head, &n4);
push(&head, &n5);
printStack(head);
void * n;
pop(&head, &n);
cout << "popped " << *(static_cast<int*>(n)) << endl;
pop(&head, &n);
cout << "popped " << *(static_cast<int*>(n)) << endl;
cout << endl;

Multi-Threaded
Programming II Native Thread
for Win32 (A)
Multi-Threaded
Programming II Native Thread
for Win32 (B)

printStack(head);

Multi-Threaded
Programming II Native Thread
for Win32 (C)
Multi-Threaded
Programming II C++ Thread for
Win32
Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads
MultiThreading/Parallel
Programming IPC

cout << "deleting stack..." << endl;


deleteStack(&head);
printStack(head);
}

Output:
50 40 30 20 10
popped 50
popped 40
30 20 10

Multi-Threaded
http://www.bogotobogo.com/cplusplus/linkedlist.php

25/47

12/26/2014

C++ Tutorial: Linked List - 2014

Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)
Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)

deleting stack...
Empty!

EXAMPLE 7 - STACK CLASS USING LINKED LIST

Multithread
Debugging

#include <iostream>

Object
Returning

using namespace std;

Object Slicing
and Virtual
Table
OpenCV with
C++
Operator
Overloading I
Operator
Overloading II self assignment
Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays
Preprocessor Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)
Stack Unwinding
Standard
Template
Library (STL) I -

class Stack
{
public:
Stack();
~Stack();
void push(int);
int pop();
int peek();
friend void print(Stack&);
private:
typedef struct node {
node *next;
int data;
} NODE;
NODE *top;
};
Stack::Stack()
{
top = NULL;
}
Stack::~Stack()
{
while(top) {
NODE *tmp = top;
top = top->next;
delete tmp;
}
}
void Stack::push(int n)
{
NODE *ptr = new NODE;
ptr->next = top;
ptr->data = n;
top = ptr;
}
int Stack::pop()
{
NODE *tmp = top;
int val = top->data;
top = top->next;

http://www.bogotobogo.com/cplusplus/linkedlist.php

26/47

12/26/2014

C++ Tutorial: Linked List - 2014

Vector & List


Standard
Template
Library (STL) II Maps
Standard
Template
Library (STL) II unordered_map
Standard
Template
Library (STL) II Sets
Standard
Template
Library (STL) III
- Iterators
Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V
- Function
Objects
Static Variables
and Static Class
Members
String
String II sstream etc.
Taste of
Assembly

delete tmp;
return val;
}
int Stack::peek()
{
return top->data;
}
void print(Stack &s)
{
Stack::NODE *cur = s.top;
while(cur) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
int main()
{
Stack *st = new Stack;
st->push(10);
st->push(20);
st->push(30);
st->push(40);
st->push(50);
print(*st);
st->pop();
st->pop();
print(*st);
cout << "current top=" << st->peek();
return 0;
}

Templates
Template
Specialization
Template
Specialization Traits
Template
Implementation
& Compiler (.h
or .cpp?)

Output:
50 40 30 20 10
30 20 10
current top=30

The this Pointer


Type Cast
Operators
Upcasting and
Downcasting
Virtual
Destructor &
boost::shared_ptr
Virtual
Functions

Programming
Questions and
Solutions

EXAMPLE 7B - STACK CLASS USING LINKED LIST


The code below is almost the same as the code in Example 6 except it's using Stack class.
The code below is almost the same as the code in Example 7 except it's using void* for the
data type.
#include <iostream>
using namespace std;
class Stack
{
public:
Stack();

http://www.bogotobogo.com/cplusplus/linkedlist.php

27/47

12/26/2014

C++ Tutorial: Linked List - 2014

Strings and
Arrays
Linked List
Recursion
Bit Manipulation
Small Programs
(string, memory
functions etc.)
Math &
Probability

~Stack();
void push(void *data);
void *pop();
void print();
protected:
typedef struct Element {
struct Element *next;
void *data;
} Element;
Element *top;
};

Multithreading
140 Questions
by Google

Qt 5
EXPRESS...

Win32 DLL ...

Articles On C++

What's new in
C++11...
C++11 Threads
EXPRESS...
OpenCV...

Stack::Stack() {
top = NULL;
}
Stack::~Stack() {
while(top) {
Element *elm = top->next;
delete top;
top = elm;
}
}
void Stack::push(void *data) {
Element *elm = new Element;
elm->data = data;
elm->next = top;
top = elm;
}
void *Stack::pop() {
void *data;
if(top == NULL) return data;
data = top->data;
Element *elm = top;
top = elm->next;
delete elm;
return data;
}
void Stack::print() {
Element *elm = top;
while(elm) {
cout << *(static_cast<int*>(elm->data)) << " " ;
elm = elm->next;
}
cout << endl;
}
int main()
{
Stack *st = new Stack;
int n1 = 10;
int n2 = 20;
int n3 = 30;
int n4 = 40;
int n5 = 50;
st->push(&n1);
st->push(&n2);
st->push(&n3);

http://www.bogotobogo.com/cplusplus/linkedlist.php

28/47

12/26/2014

C++ Tutorial: Linked List - 2014

st->push(&n4);
st->push(&n5);
st->print();
cout << *(static_cast<int*>(st->pop()))<< " poped\n";
cout << *(static_cast<int*>(st->pop()))<< " poped\n";
st->print();
cout << endl;
}

Output:
50 40 30 20 10
50 poped
40 poped
30 20 10

EXAMPLE 7C - STACK CLASS USING LINKED LIST WITH QUERY FOR MINIMUM
VALUE
This stack class can return its minimum element. All operations (push(), pop(), and
peekMin()) are O(1) not O(n). Usual approach for query would be traverse each element to get
the minimum, and it will ends up with O(n) complexity. So, to have constant time operation,
we need keep track of the minimum. We could have a global minimum value, however, it has
a problem when the stack with the value popped. Then, we need to update the global min
value which may take O(n) operation.
In the code below, each stack gets its own min-value at the time when it was pushed by
comparing the minimum of the previous top stack. When the top stack popped, the code
checks if the top stack's minimum value is the global min.
In summary, this code will get the stacks minimum value by peeking the top only, using
peekMin() which returns the min-value for the top stack.
#include <iostream>
using namespace std;
#define MIN(a,b) (a < b ? a : b)
class Stack
{
public:
Stack();
~Stack();
void push(int);
int pop();
int peek();
int peekMin();
friend void print(Stack&);
private:
typedef struct node {
node *next;
int data;
int min;
} NODE;
http://www.bogotobogo.com/cplusplus/linkedlist.php

29/47

12/26/2014

C++ Tutorial: Linked List - 2014

NODE *top;
};
Stack::Stack()
{
top = NULL;
}
Stack::~Stack()
{
while(top) {
NODE *tmp = top;
top = top->next;
delete tmp;
}
}
void Stack::push(int n)
{
NODE *ptr = new NODE;
ptr->next = top;
ptr->data = n;
// currently empty (top is NULL)
if(top == NULL)
ptr->min = n;
else
ptr->min = MIN(n, top->min);
top = ptr;
}
int Stack::pop()
{
NODE *tmp = top;
int val = top->data;
top = top->next;
delete tmp;
cout << "pop " << val << endl;
return val;
}
int Stack::peek()
{
return top->data;
}
int Stack::peekMin()
{
return top->min;
}
void print(Stack &s)
{
Stack::NODE *cur = s.top;
while(cur) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

30/47

12/26/2014

C++ Tutorial: Linked List - 2014

List of C++
Tutorials
C++ Home
Algorithms &
Data Structures
in C++ ...
Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)
auto_ptr
Binary Tree
Example Code
Blackjack with
Qt

int main()
{
Stack *st = new Stack;
st->push(40);
st->push(50);
st->push(20);
st->push(10);
st->push(30);
print(*st);
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
print(*st);
cout << "current top=" << st->peek();
return 0;
}

Output:
30 10 20 50 40
minimum = 10
pop 30
minimum = 10
pop 10
minimum = 20
pop 20
minimum = 40
pop 50
minimum = 40
40
current top=40

Boost shared_ptr,
weak_ptr, mpl,
lambda, etc.
Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...
Classes and
Structs
Constructor
C++11(C++0x):
rvalue
references,
move
constructor, and
lambda, etc.
C++ API Testing
C++ Keywords const, volatile,
etc.
Debugging

EXAMPLE 7D - STACK CLASS USING LINKED LIST WITH QUERY FOR MINIMUM
VALUE (ADDITIONAL STACK)
Even though the code in Example 7C can keep track of the minimum of the stack, it is obvious
that the code is wasting resources. Suppose, we push the element with the minimum first: 10,
20, 30, 40 ... with increasing order. In that case, the every stack element has additional
member for minimum value of 10. However, if we have separate stack just for minimum, we
end up having only one stack because we do not save the values which are greater than the
min-value.
Here is the code using separate stack (StackWithMin class) just for the minimum value.
#include <iostream>
using namespace std;
typedef struct node {
node *next;
int data;

http://www.bogotobogo.com/cplusplus/linkedlist.php

31/47

12/26/2014

C++ Tutorial: Linked List - 2014

Crash &
Memory Leak

} NODE;

Design Patterns
in C++ ...

class Stack
{
public:
Stack();
virtual ~Stack();
virtual void push(int);
virtual int pop();
virtual int peekMin();
int peek();
friend void print(Stack&);

Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III
- Eclipse CDT
Plugin for gcc
ARM Toolchain
Exceptions
Friend
Functions and
Friend Classes
fstream: input &
output
Function
Overloading
Functors
(Function
Objects) I Introduction
Functors
(Function
Objects) II Converting
function to
functor
Functors
(Function
Objects) General
Git and GitHub
Express...
GTest (Google
Unit Test) with
Visual Studio
2012
Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)

private:
bool empty();
NODE *top;
};
Stack::Stack()
{
top = NULL;
}
Stack::~Stack()
{
while(top) {
NODE *tmp = top;
top = top->next;
delete tmp;
}
}
void Stack::push(int n)
{
NODE *ptr = new NODE;
ptr->next = top;
ptr->data = n;
top = ptr;
}
int Stack::pop()
{
NODE *tmp = top;
if(!empty()) {
int val = top->data;
top = top->next;
delete tmp;
cout << "pop " << val << endl;
return val;
}
else {
cout << "empty! " << endl;
return -1;
}
}
int Stack::peek()
{
if(!empty()) return top->data;
return -1;
}

http://www.bogotobogo.com/cplusplus/linkedlist.php

32/47

12/26/2014

C++ Tutorial: Linked List - 2014

Linked List
Basics
Linked List
Examples

bool Stack::empty()
{
if(top == NULL) return true;
return false;
}

make & CMake


make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.
Multi-Threaded
Programming II Native Thread
for Win32 (A)
Multi-Threaded
Programming II Native Thread
for Win32 (B)
Multi-Threaded
Programming II Native Thread
for Win32 (C)
Multi-Threaded
Programming II C++ Thread for
Win32
Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads
MultiThreading/Parallel
Programming IPC
Multi-Threaded
Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)
Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)
Multithread
Debugging
Object
Returning
Object Slicing
and Virtual
Table
OpenCV with
C++
Operator
Overloading I

int Stack::peekMin()
{
return -1;
}
void print(Stack &s)
{
NODE *cur = s.top;
while(cur) {
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
class StackWithMin : public Stack
{
public:
StackWithMin();
~StackWithMin();
void push(int);
int pop();
int peekMin();
private:
bool empty();
NODE* top;
};
StackWithMin::StackWithMin()
{
top = NULL;
}
StackWithMin::~StackWithMin()
{
while(top) {
NODE *tmp = top;
top = top->next;
delete tmp;
}
}
void StackWithMin::push(int n)
{
if(top){
// push only if it's smaller than the top min
if(n < top->data) {
NODE *ptr = new NODE;
ptr->next = top;
ptr->data = n;
top = ptr;
}
}
// if empty, just push the new element
else {
NODE *ptr = new NODE;

http://www.bogotobogo.com/cplusplus/linkedlist.php

33/47

12/26/2014

C++ Tutorial: Linked List - 2014

ptr->next = top;
ptr->data = n;
top = ptr;

Operator
Overloading II self assignment

Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays
Preprocessor Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)
Stack Unwinding
Standard
Template
Library (STL) I Vector & List
Standard
Template
Library (STL) II Maps
Standard
Template
Library (STL) II unordered_map
Standard
Template
Library (STL) II Sets
Standard
Template
Library (STL) III
- Iterators
Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V

Stack::push(n);
}
int StackWithMin::pop()
{
int popped = Stack::pop();
if(empty()) {
cout << "empty min stack" << endl;
return -1;
}
if(popped == top->data) {
NODE *tmp = top;
if(top->next) {
top = top->next;
}
else {
top = NULL;
}
delete tmp;
}
return popped;
}
int StackWithMin::peekMin()
{
if(!empty()) return top->data;
cout << "empty min stack!" << endl;
return -1;
}
bool StackWithMin::empty()
{
if(top == NULL) return true;
return false;
}
int main()
{
Stack *st = new StackWithMin;
st->push(40);
st->push(50);
st->push(20);
st->push(10);
st->push(30);
print(*st);
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
st->pop();
cout << "minimum = " << st->peekMin() << endl;
print(*st);

http://www.bogotobogo.com/cplusplus/linkedlist.php

34/47

12/26/2014

C++ Tutorial: Linked List - 2014

- Function
Objects
Static Variables
and Static Class
Members
String

cout << "current top=" << st->peek();


return 0;
}

Output:

String II sstream etc.


Taste of
Assembly
Templates
Template
Specialization
Template
Specialization Traits
Template
Implementation
& Compiler (.h
or .cpp?)
The this Pointer
Type Cast
Operators
Upcasting and
Downcasting
Virtual
Destructor &
boost::shared_ptr
Virtual
Functions

30 10 20 50 40
minimum = 10
pop 30
minimum = 10
pop 10
minimum = 20
pop 20
minimum = 40
pop 50
minimum = 40
pop 40
empty min stack!
minimum = -1

Programming
Questions and
Solutions

Strings and
Arrays
Linked List
Recursion
Bit Manipulation
Small Programs
(string, memory
functions etc.)
Math &
Probability

EXAMPLE 8 QUEUE STRUCT : USING LINKED LIST


#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
node *next;
};
typedef struct node node_t;

Multithreading
140 Questions
by Google

Qt 5
EXPRESS...

node_t *head = NULL;


void push(int n)
{
node_t *newNode = (node_t *)malloc(sizeof(node_t));
newNode->data = n;
newNode->next = NULL;

Win32 DLL ...

http://www.bogotobogo.com/cplusplus/linkedlist.php

if(head == NULL) {
head = newNode;
35/47

12/26/2014

C++ Tutorial: Linked List - 2014

return;

Articles On C++

}
node_t *cur = head;
while(cur) {
if(cur->next==NULL) {
cur->next = newNode;
return;
}
cur = cur->next;
}

What's new in
C++11...
C++11 Threads
EXPRESS...
OpenCV...

}
void pop()
{
if(head==NULL) return;
node_t *tmp = head;
head = head->next;
free(tmp);
}
void display()
{
node_t *cur = head;
while(cur) {
printf("%3d",cur->data);
cur = cur->next;
}
printf("\n");
}
int main()
{
push(1);push(2);push(3);push(4);push(5);display();
pop();display();
pop();display();
pop();display();
pop();display();
pop();display();
return 0;
}

Output is:
1
2
3
4
5

2 3 4 5
3 4 5
4 5
5

EXAMPLE 8B - QUEUE CLASS: USING LINKED LIST


First one becomes head, so when it pops, head will be popped.
http://www.bogotobogo.com/cplusplus/linkedlist.php

36/47

12/26/2014

C++ Tutorial: Linked List - 2014

#include <iostream>
using namespace std;
class Queue
{
public:
Queue();
~Queue();
void push(int);
int pop();
void print();
private:
typedef struct Node {
Node *next;
int data;
} NODE;
NODE* head;
};
Queue::Queue()
{
head = NULL;
}
Queue::~Queue()
{
if(head == NULL) return;
NODE *cur = head;
while(cur) {
Node *ptr = cur;
cur = cur->next;
delete ptr;
}
}
void Queue::push(int n)
{
if(head == NULL) {
head = new NODE;
head->data = n;
head->next = NULL;
return;
}
NODE *cur = head;
while(cur) {
if(cur->next == NULL) {
NODE *ptr = new NODE;
ptr->data = n;
ptr->next = NULL;
cur->next = ptr;
return;
}
cur = cur->next;
}
}
void Queue::print()
{
if(head==NULL) return;
Node *cur = head;
while(cur) {
cout << cur->data << " ";
http://www.bogotobogo.com/cplusplus/linkedlist.php

37/47

12/26/2014

C++ Tutorial: Linked List - 2014

cur = cur->next;
}
cout << endl;
}
int Queue::pop()
{
if(head == NULL) {
cout << "empty estack!" << endl;
return NULL;
}
NODE *tmp = head;
int value = head->data;
if(head->next) {
head = head->next;
}
// pop the last element (head)
else {
delete tmp;
head = NULL;
}
cout << "pop: " << value << endl;;
return value;
}
int main()
{
Queue *que = new Queue();
que->push(10);
que->push(20);
que->push(30);
que->push(40);
que->push(50);
que->print();
que->pop();que->print();
que->pop();que->print();
que->pop();que->print();
que->pop();que->print();
que->pop();que->print();
que->pop();que->print();
return 0;
}

Output:
10 20 30 40 50
pop: 10
20 30 40 50
pop: 20
30 40 50
pop: 30
40 50
pop: 40
50
pop: 50

List of C++
Tutorials
http://www.bogotobogo.com/cplusplus/linkedlist.php

38/47

12/26/2014

C++ Tutorial: Linked List - 2014

C++ Home
Algorithms &
Data Structures
in C++ ...
Application (UI)
- using Windows
Forms (Visual
Studio
2013/2012)
auto_ptr
Binary Tree
Example Code
Blackjack with
Qt
Boost shared_ptr,
weak_ptr, mpl,
lambda, etc.
Boost.Asio
(Socket
Programming Asynchronous
TCP/IP)...
Classes and
Structs

EXAMPLE 9 - FINDING INTERSECTION AND UNION OF TWO LINKED LIST


The following code finds intersection/union of two linked list and puts it into a new linked list.
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
void add(struct node **head, int n)
{
struct node *cur;
struct node *new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = n;
new_node->next = NULL;
if(*head == NULL) {
*head = new_node;
return;
}
cur = *head;
while(cur) {
if(cur->next == NULL) {
cur->next = new_node;
return;
}
cur = cur->next;
}

Constructor
C++11(C++0x):
rvalue
references,
move
constructor, and
lambda, etc.
C++ API Testing
C++ Keywords const, volatile,
etc.
Debugging
Crash &
Memory Leak
Design Patterns
in C++ ...
Dynamic Cast
Operator
Eclipse CDT /
JNI (Java Native
Interface) /
MinGW
Embedded
Systems
Programming I Introduction
Embedded
Systems
Programming II gcc ARM
Toolchain and
Simple Code on
Ubuntu and
Fedora
Embedded
Systems
Programming III

}
bool isDuplicate(struct node *head, int n)
{
struct node* cur = head;
while(cur) {
if(cur->data == n) return true;
cur = cur->next;
}
return false;
}
struct node *getIntersection(struct node *headA, struct node *headB)
{
struct node *curA = headA;
struct node *curB = headB;
struct node *result = NULL;
if(curA == NULL || curB == NULL) return NULL;
while(curA) {
while(curB) {
if(curA->data == curB->data) {
add(&result, curA->data);
}
curB = curB->next;
}
curB = headB;
curA = curA->next;

http://www.bogotobogo.com/cplusplus/linkedlist.php

39/47

12/26/2014

C++ Tutorial: Linked List - 2014

- Eclipse CDT
Plugin for gcc
ARM Toolchain

}
return result;
}

Exceptions
Friend
Functions and
Friend Classes
fstream: input &
output

struct node *getUnion(struct node *headA, struct node *headB)


{
struct node *cur;
struct node *result = NULL;
if(headA == NULL && headB == NULL) return NULL;

Function
Overloading

cur = headA;
while(cur) {
add(&result, cur->data);
cur = cur->next;
}

Functors
(Function
Objects) I Introduction
Functors
(Function
Objects) II Converting
function to
functor

cur = headB;
while(cur) {
/* check if the new data is already there */
if(!isDuplicate(result, cur->data)) {
add(&result, cur->data);
}
cur = cur->next;
}
return result;

Functors
(Function
Objects) General
Git and GitHub
Express...
GTest (Google
Unit Test) with
Visual Studio
2012
Inheritance &
Virtual
Inheritance
(multiple
inheritance)
Libraries Static, Shared
(Dynamic)
Linked List
Basics
Linked List
Examples
make & CMake

}
void display(struct node *head)
{
if(head == NULL) return;
struct node *cur = head;
while(cur) {
cout << cur->data << ' ';
cur = cur->next;
}
cout << endl;
}
int main()
{
struct node *myListA = NULL;
struct node *myListB = NULL;
struct node *intersectionList = NULL;
struct node *unionList = NULL;

make (gnu)
Memory
Allocation
Multi-Threaded
Programming Terminology Semaphore,
Mutex, Priority
Inversion etc.
Multi-Threaded
Programming II Native Thread
for Win32 (A)
Multi-Threaded
Programming II Native Thread
for Win32 (B)
http://www.bogotobogo.com/cplusplus/linkedlist.php

add(&myListA,10);
add(&myListA,20);
add(&myListA,30);
add(&myListA,40);
add(&myListA,50);
add(&myListA,60);
add(&myListA,70);
cout << "List A: ";
display(myListA);
add(&myListB,10);
add(&myListB,30);
add(&myListB,50);
add(&myListB,70);
add(&myListB,90);
add(&myListB,110);
add(&myListB,130);
40/47

12/26/2014

C++ Tutorial: Linked List - 2014

cout << "List B: ";


display(myListB);

Multi-Threaded
Programming II Native Thread
for Win32 (C)

cout << "Intersection of A and B: ";


intersectionList = getIntersection(myListA, myListB);
display(intersectionList);

Multi-Threaded
Programming II C++ Thread for
Win32

cout << "Union of A and B: ";


unionList = getUnion(myListA, myListB);
display(unionList);

Multi-Threaded
Programming III
- C/C++ Class
Thread for
Pthreads
MultiThreading/Parallel
Programming IPC
Multi-Threaded
Programming
with C++11 Part
A (start, join(),
detach(), and
ownership)
Multi-Threaded
Programming
with C++11 Part
B (Sharing Data
- mutex, and
race conditions,
and deadlock)

return 0;
}

Output is:
List A: 10 20 30 40 50 60 70
List B: 10 30 50 70 90 110 130
Intersection of A and B: 10 30 50 70
Union of A and B: 10 20 30 40 50 60 70 90 110 130

Multithread
Debugging
Object
Returning
Object Slicing
and Virtual
Table
OpenCV with
C++
Operator
Overloading I
Operator
Overloading II self assignment
Pass by Value
vs. Pass by
Reference
Pointers
Pointers II - void
pointers &
arrays
Pointers III pointer to
function & multidimensional
arrays

EXAMPLE 10 - ANOTHER EXAMPLE OF GENERIC LINKED LIST


The following example is another example of generic use of linked list. It will be used as a
base for doubly linked list later.
#include <iostream>
using namespace std;
template <typename T>
class List
{
struct Node
{
T data;
Node *next;
Node(T d, Node *n = 0):data(d), next(n) {}
};
Node *head;
public:

Preprocessor Macro
Private
Inheritance
Python & C++
with SIP
(Pseudo)http://www.bogotobogo.com/cplusplus/linkedlist.php

List(Node *h = 0):head(h){}
~List();
void insert(Node *loc, T d);
void push_back(T d);
void push_front(T d);
T pop_back();
T pop_front();
41/47

12/26/2014

C++ Tutorial: Linked List - 2014

random
numbers in C++
References for
Built-in Types
Socket - Server
& Client
Socket - Server
& Client with Qt
(Asynchronous /
Multithreading /
ThreadPool
etc.)
Stack Unwinding
Standard
Template
Library (STL) I Vector & List
Standard
Template
Library (STL) II Maps
Standard
Template
Library (STL) II unordered_map
Standard
Template
Library (STL) II Sets
Standard
Template
Library (STL) III
- Iterators
Standard
Template
Library (STL) IV
- Algorithms
Standard
Template
Library (STL) V
- Function
Objects
Static Variables
and Static Class
Members
String
String II sstream etc.
Taste of
Assembly
Templates
Template
Specialization
Template
Specialization Traits
Template
Implementation
& Compiler (.h
or .cpp?)
The this Pointer

void erase(Node *loc);


void display();
Node *search(T d);
};
// destructor
template <typename T>
List<T>::~List()
{
Node *tmp;
while(head) {
tmp = head;
head = head->next;
delete tmp;
}
}
// insert d before loc
template <typename T>
void List<T>::insert(Node *loc, T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
if(loc == head) {
push_front(d);
return;
}
Node *cur = head;
while(cur->next) {
if(cur->next == loc) {
new_node->next = cur->next;
cur->next = new_node;
return ;
}
cur = cur->next;
}
}
template <typename T>
void List<T>::push_back(T d)
{
Node *new_node = new Node(d,0);
if(!head) {
head = new_node;
return;
}
Node *cur = head;
while(cur) {
if(!cur->next) {
cur->next = new_node;
return;
}
cur = cur->next;
}
}
template <typename T>
void List<T>::push_front(T d)
{

http://www.bogotobogo.com/cplusplus/linkedlist.php

42/47

12/26/2014

C++ Tutorial: Linked List - 2014

Node *new_node = new Node(d,0);


if(!head) {
head = new_node;
return;
}
new_node->next = head;
head = new_node;
return;

Type Cast
Operators
Upcasting and
Downcasting
Virtual
Destructor &
boost::shared_ptr
Virtual
Functions

Programming
Questions and
Solutions

Strings and
Arrays
Linked List
Recursion
Bit Manipulation
Small Programs
(string, memory
functions etc.)
Math &
Probability
Multithreading
140 Questions
by Google

Qt 5
EXPRESS...

Win32 DLL ...

Articles On C++

What's new in
C++11...
C++11 Threads
EXPRESS...

}
template <typename T>
T List<T>::pop_back()
{
Node *cur = head;
while(cur) {
if(!cur->next) {
T data (cur->data);
delete cur;
head = NULL;
return data;
}
else {
if(!cur->next->next) {
T data (cur->next->data);
cur->next = NULL;
delete cur->next;
return data;
}
}
cur = cur->next;
}
return NULL;
}
template <typename T>
T List<T>::pop_front()
{
if(!head) return NULL;
Node *tmp = head;
T data (head->data);
if(head->next) {
head = head->next;
delete tmp;
return data;
}
delete tmp;
head = NULL;
return data;
}

OpenCV...

template <typename T>


void List<T>::erase(Node *loc)
{
if(loc == head) {
Node *tmp = head;
head = head->next;
delete tmp;
return;
}
Node *cur = head;
while(cur) {
if(cur->next == loc) {
http://www.bogotobogo.com/cplusplus/linkedlist.php

43/47

12/26/2014

C++ Tutorial: Linked List - 2014

cur->next = loc->next;
delete loc;
}
cur = cur->next;
}
}
template <typename T>
typename List<T>::Node* List<T>::search(T d)
{
if(!head) return NULL;
Node* cur = head;
while(cur) {
if(cur->data == d) return cur;
cur = cur->next;
}
return NULL;
}
template <typename T>
void List<T>::display()
{
if(!head) return;
Node *cur = head;
while(cur) {
cout << cur->data << " " << endl;
cur = cur->next;
}
cout << endl;
}
int main()
{
List<int> *myList = new List<int>(NULL);
cout << "push_back() 20, 30 40, 50\n\n";
myList->push_back(20);
myList->push_back(30);
myList->push_back(40);
myList->push_back(50);
myList->display();
cout << "push_front() 10\n\n";
myList->push_front(10);
myList->display();
cout << "erase 30\n\n";
myList->erase(myList->search(30));
myList->display();
cout << "insert 30 before 40\n\n";
myList->insert(myList->search(40),30);
myList->display();
cout << "pop_back()\n";
cout << myList->pop_back() << " just back popped\n\n";
myList->display();
cout << "pop_front()\n";
cout << myList->pop_front() << " just front popped\n\n";
myList->display();

http://www.bogotobogo.com/cplusplus/linkedlist.php

44/47

12/26/2014

C++ Tutorial: Linked List - 2014

return 0;
}

Output:
push_back() 20, 30 40, 50
20
30
40
50
push_front() 10
10
20
30
40
50
erase 30
10
20
40
50
insert 30 before 40
10
20
30
40
50
pop_back()
50 just back popped
10
20
30
40
pop_front()
10 just front popped
20
30
40

LIST OF LINKED LIST EXAMPLES OF THIS PAGE


http://www.bogotobogo.com/cplusplus/linkedlist.php

45/47

12/26/2014

C++ Tutorial: Linked List - 2014

Example 1
When the head of the list is not a global pointer.
Example 2 and Example 3
When the head of the list is a global pointer.
There are some implementation differences between these two examples.
Example 4
Used class & structure in that class.
Example 5A
Detecting circular (loop) linked list.
Example 5B
Detecting circular (loop) linked list (Generic Class with Template).
Example 6
Stack with linked list data structure.
Example 7
Class Stack with linked list data structure.
Example 7B
Class Stack with linked list data structure.
Example 7C
Class Stack using linked list with query for minimum value.
Example 7D
Stack Class Using Linked List with Query for Minimum Value (additional stack).
Example 8
Queue Struct with linked list data structure.
Example 8B
Queue Class with linked list data structure.
Example 9
Finding intersection and union of two linked lists.
Example 10
Generic linked lists.
Also, there are set of linked list samples:
quiz.
Linked List Basic.

Bogotobogo Image / Video Processing

Computer Vision & Machine Learning


with OpenCV, MATLAB, FFmpeg, and scikit-learn.

I hope this site is informative and helpful.

http://www.bogotobogo.com/cplusplus/linkedlist.php

46/47

12/26/2014

C++ Tutorial: Linked List - 2014

Bogotobogo's Video Streaming Technology


with FFmpeg, HLS, MPEG-DASH, H.265 (HEVC)

I hope this site is informative and helpful.

Bogotobogo's contents
To see more items, click left or right arrow.

I hope this site is informative and helpful.

C++ Video

In C++

C++ Method C++ Learn

Search
Custom Search

Home | About Us | products | Our Services | Contact Us | Bogotobogo 2014 | Bogotobogo

http://www.bogotobogo.com/cplusplus/linkedlist.php

47/47

Vous aimerez peut-être aussi