How to create Linked list using C/C++
2015-02-10 15:33
561 查看
From: http://www.codeproject.com/Articles/24684/How-to-create-Linked-list-using-C-C
Introduction
Linked list is one of the fundamental datastructures, and canbe used to implement other datastructures. In a linked list there are different numbers of nodes. Each node is consists of two fields. The first field holds the value or dataand the secondfield holds the reference to the nextnode or null if the linked list is empty.Figure: Linked listPseudocode:int a = 50 // initialize variable aThe singly-linked list is the easiest of the linked list, which has one link per node.
Pointer
To create linked list in C/C++ we must have a clear understanding about pointer. Now I will explain inbrief what is pointer and how it works.A pointer is a variable that contains the address of a variable. The question is why we need pointer? Or why it is so powerful? The answer is they havebeen part of the C/C++ language and so we have to use it. Using pointer we can pass argument to the functions.Generally we pass themby value as a copy. So we cannot change them. But if we pass argument using pointer, we can modify them. To understand about pointers, we must know how computer store variable and its value. Now, I will show it here in a very simpleway.Let us imagine that a computer memory is a long array and every array location has a distinct memory location.Collapse | CopyCodeint a = 50 // initialize variable aFigure: Variable value store inside an arrayIt is like a house which has an address and this house has only one room. So the full address is-Name of the house: aName of the person/value who live here is: 50House Number: 4010If we want to change the person/value of this house, the conventional way is, type this code line
a = 100 // new initializationBut using pointer we can directly go to the memory location of 'a' and change the person/value of this house without disturbing ‘a’. This is the main point about pointer.Now the question is how we can use pointer. Type this code line:
int *b; // declare pointerbWe transfer the memory location of
ato
b.
b = &a; // the unary operator & gives the address of an objectFigure: Integer pointer
bstore the address of the integer variable
aNow, we can change the value of
awithout accessing
a.
*b = 100; // change the value of 'a' using pointer ‘b’ cout<<a; // show the output of 'a'When you order the computer to access to access
*b, it reads the content inside
b, which is actually the address of
athen it will followthe address and comes to the house of
aand read
a`s content which is 50.Now the question is, if it is possible to read and change the content of
bwithout accessing
b? The answer is affirmative. We can create a pointer of pointer.
int **c; //declare a pointer to a pointer c = &b; //transfer the address of ‘b’ to ‘c’So, we can change the value of
awithout disturbing variable
aand pointer
b.
**c = 200; // change the value of ‘a’ using pointer to a pointer ‘c’ cout<<a; // show the output of aNow the total code is:
#include<span class="code-keyword"><iostream></span>using namespace std;int main(){int a = 50; // initialize integer variable acout<<"The value of 'a': "<<a<<endl; // show the output of aint *b; // declare an integer pointerbb = &a; // transfer the address of 'a' to pointer 'b'*b = 100; // change the value of 'a' using pointer 'b'cout<<"The value of 'a' using *b: "<<a<<endl;// show the output of aint **c; // declare an integer pointer to pointer 'c'c = &b; // transfer the address of 'b' to pointer to pointer 'c'**c = 200; // change the value of 'a' using pointer to pointer 'c'cout<<"The value of 'a' using **c: "<<a<<endl;// show the output of areturn 0;}Output:This program will give you the inside view of the pointer.
#include<span class="code-keyword"><iostream></span>using namespace std;int main(){int a = 50; // initialize integer variable acout<<"Value of 'a' = "<<a<<endl; // show the output of acout<<"Memory address of 'a': "<<&a<<endl; // show the address of acout<<endl;int *b; // declare an integer pointerbb = &a; // transfer the address of 'a' to pointer 'b'cout<<"Value of Pointer 'b': "<<*b<<endl; // show the output of *bcout<<"Content of Pointer 'b': "<<b<<endl; // show the content of *bcout<<"Memory address of Pointer 'b': "<<&b<<endl; // show the address of *bcout<<endl;int **c; // declare an integer pointer to a pointerc = &b; // transfer the address of 'b' to 'c'cout<<"Value of Pointer 'c': "<<**c<<endl; // show the output of **ccout<<"Content of Pointer 'c': "<<c<<endl; // show the content of **ccout<<"Memory address of Pointer 'c': "<<&c<<endl; // show the address of **ccout<<endl;return 0;}Output:We can observe that the memory address of
aand the content of pointer
bis same. The content of pointer
cand the memory address of
bissame.
Linked list operation
Now we have a clear view about pointer. So we are ready for creating linked list.Linked list structuretypedef struct node { int data; // will store information node *next; // the reference to the nextnode };First we create a structure “node”. It has two members and first is
int datawhich will store the information and second is
node *nextwhich willhold the address of the nextnode. Linked list structure is complete so now we will create linked list. We can insert datain the linked list from 'front' and at the same time from 'back’. Now we will examine how we can insert datafrom front in the linkedlist.
1) Insert from front
At first initialize node type.node *head = NULL; //empty linked listThen we take the datainput from the user and store in the
node infovariable. Create a temporary node
node*tempand allocate space for it.
node*temp; //create a temporary node temp = (node*)malloc(sizeof(node)); //allocate space for nodeThen place
infoto
temp->data. So the first field of the
node*tempis filled. Now
temp->nextmustbecome a part of the remaining linked list (although now linked list is emptybut imagine that we have a 2 node linked list andhead is pointed at the front) So
temp->nextmust copy theaddress of the
*head(Because we want insert at first) and we also want that
*headwill always point at front. So
*headmust copy the addressof the
node*temp.Figure: Insert at firsttemp->data= info; // store data(first field)
temp->next=head; // store the address of the pointerhead(second field) head = temp; // transfer the address of 'temp' to 'head'
2) Traverse
Now we want to see the information stored inside the linked list. We create node*temp1. Transfer the address of
*headto
*temp1. So
*temp1isalso pointed at the front of the linked list. Linked list has 3 nodes.We can get the datafrom first node using
temp1->data. To get datafrom second node, we shift
*temp1to the second node. Now we can get the datafrom second node.
while(temp1!=NULL ) { cout<<temp1->data<<" ";// show the datain the linked list temp1 =temp1->next; // transfer the address of 'temp->next' to 'temp' }Figure: TraverseThis process will run until the linked list’s nextis NULL.
3) Insert fromback
Insert datafromback is very similar to the insert from front in the linked list. Here the extra job is to find the last node of the linked list.node*temp1; // create a temporary nodetemp1=(node*)malloc(sizeof(node)); // allocate space for nodetemp1 =head; // transfer the address of 'head' to 'temp1'while(temp1->next!=NULL) // go to the last nodetemp1 =temp1->next;//tranfer the address of 'temp1->next' to 'temp1'Now, Create a temporary node
node*tempand allocate space for it. Then place
infoto temp->data, so the first field of the node
node*tempisfilled.
node*tempwillbe the last node of the linked list. For this reason,
temp->nextwillbe NULL. To create a connectionbetween linked listand the new node, the last node of the existing linked list
node*temp1`s second field
temp1->nextis pointed to
node *temp.Figure: Insert at last
node*temp; // create a temporary nodetemp = (node*)malloc(sizeof(node)); // allocate space for nodetemp->data= info; // store data(first field)temp->next= NULL; // second field willbe null(last node)temp1->next= temp; // 'temp' node willbe the last node
4) Insert after specified number of nodes
Insert datain the linked list after specified number of node is a littlebit complicated. But the idea is simple. Suppose, we want to add a node after 2nd position. So, the new node mustbe in 3rd position. The first step is to go the specified number ofnode. Let, node*temp1 is pointed to the 2nd node now.cout<<"ENTER THE NODE NUMBER:";cin>>node_number; // take the node number from usernode*temp1; // create a temporary nodetemp1 = (node*)malloc(sizeof(node)); // allocate space for nodetemp1 =head;for( int i = 1 ; i < node_number ; i++ ){temp1 =temp1->next; // go to the nextnodeif(temp1 == NULL ){cout<<node_number<<" node is not exist"<< endl;break;}}Now, Create a temporary node
node*tempand allocate space for it. Then place
infoto
temp->next, sothe first field of the node
node*tempis filled.
node*temp; // create a temporary node temp = (node*)malloc(sizeof(node)); // allocate space for node temp->data= info; // store data(first field)To establish the connectionbetween new node and the existing linked list, new node’s
nextmust pointed to the 2nd node’s (temp1)
next. The 2nd node’s (temp1) nextmust pointedto the new node(temp).
temp->next=temp1->next; //transfer the address oftemp1->nextto temp->nexttemp1->next= temp; //transfer the address of temp totemp1->nextFigure: Insert after specified number of nodes
5) Delete from front
Delete a node from linked list is relatively easy. First, we create node*temp. Transfer the address of
*headto
*temp. So
*tempispointed at the front of the linked list. We want to delete the first node. So transfer the address of
temp->nextto
headso that it now pointedto the second node. Now free the space allocated for first node.
node*temp; // create a temporary nodetemp = (node*)malloc(sizeof(node)); // allocate space for nodetemp =head; // transfer the address of 'head' to 'temp'head = temp->next; // transfer the address of 'temp->next' to 'head'free(temp);Figure: Delete at first node
6) Delete fromback
The last node`snextof the linked list always pointed to NULL. So when we will delete the last node, the previous node of last nodeis now pointed at NULL. So, we will track last node and previous node of the lastnode in the linked list. Create temporary
node *temp1and
*old_temp.
// create a temporary nodenode*temp1;temp1 = (node*)malloc(sizeof(node)); // allocate space for nodetemp1 =head; //transfer the address ofhead totemp1node *old_temp; // create a temporary nodeold_temp = (node*)malloc(sizeof(node)); // allocate space for nodewhile(temp1->next!=NULL) // go to the last node{old_temp =temp1; // transfer the address of 'temp1' to 'old_temp'temp1 =temp1->next; // transfer the address of 'temp1->next' to 'temp1'}Now
node*temp1is now pointed at the last node and
*old_tempis pointed at the previous node of the last node. Now rest of the work is very simple. Previous node of the lastnode
old_tempwillbe NULL so itbecome the last node of the linked list. Free the space allocated for last lode.
old_temp->next= NULL; // previous node of the last node is nullfree(temp1);Figure: Delete at first last
7) Delete specified number of node
To delete a specified node in the linked list, we also require to find the specified node and previous node of the specified node. Create temporarynode *temp1,
*old_tempandallocate space for it. Take the input from user to know the number of the node.
node*temp1; // create a temporary nodetemp1 = (node*)malloc(sizeof(node)); // allocate space for nodetemp1 =head; // transfer the address of 'head' to 'temp1'node *old_temp; // create a temporary nodeold_temp = (node*)malloc(sizeof(node)); // allocate space for nodeold_temp =temp1; // transfer the address of 'temp1' to 'old_temp'
cout<<"ENTER THE NODE NUMBER:"; cin>>node_number; // take location
for( int i = 1 ; i < node_number ; i++ ) { old_temp =temp1; // store previous node temp1 =temp1->next; // store current node }Now
node*temp1is now pointed at the specified node and
*old_tempis pointed at the previous node of the specified node. The previous node of the specified node must connectto the rest of the linked list so we transfer the address of
temp1->nextto
old_temp->next.Now free the space allocatedfor the specified node.
old_temp->next=temp1->next; // transfer the address of 'temp1->next' to 'old_temp->next'free(temp1);
8) Sort nodes
Linked list sorting is very simple. It is just like ordinary array sorting. First we create two temporary nodenode*temp1,
*temp2and allocate space for it. Transfer the addressof first node to
temp1and address of second node to
temp2. Now check if
temp1->datais greater than
temp2->data.If yes then exchange the data. Similarly, we perform this checking for all the nodes.
node*temp1; // create a temporary nodetemp1 = (node*)malloc(sizeof(node)); // allocate space for nodenode*temp2; // create a temporary nodetemp2 = (node*)malloc(sizeof(node)); // allocate space for nodeint temp = 0; // store temporary datavaluefor(temp1 =head ;temp1!=NULL ;temp1 =temp1->next){for( temp2 =temp1->next; temp2!=NULL ; temp2 = temp2->next){if(temp1->data> temp2->data){temp =temp1->data;temp1->data= temp2->data;temp2->data= temp;}}}
Conclusion
From the above discussions, I hope that everybody understands what linked list is and how we can create it. Now we can easily modify linked list according to our program requirement and try to use it for some real tasks. Those who still have some confusionabout linked list, for them I will now tell you a story.Once upon a time, an old man lived in a small village. The old man was very wise and knew many solutions about different problems. He had also special powers so he could talk to genie and spirits, and sometimes they granted his wishby using their specialpowers. Oneday a witch with abroom came to talk with him and ask difficult and complex issues about global warming. He was very surprisedbut patiently explained her about green house model and gave her advice about usingbiofuel in herbroom. The witch wasvery rude and greedybut she always liked to preach her nobility. So at the time of her departure, she wanted to grant only two wishes. The old man asked her why she only granted two wishes. He also reminded her that whenever genie comes he granted two wishes.”What I am look like" the witch asked angrily,” Ablank check?" The old manbrewed a plan. He told her that his first wish was to get a super computer.” It is granted", the witch announced loudly.” Then my second wish is to have another two wishes”, the oldman said very slowly. The witch was shell shocked. "It is also granted”, the witch said and left the place very quickly with herbroom.You may ask yourself why the witch was surprised. First, the witch granted two witches. One was fulfilled and for the second wish, the old man wanted another two wish. “What’s thebig idea?” you can ask me,” The witch can also fulfill this wish”. Certainly,the witch can grant his wish. But what will happen if the old man wants to extend his second wish to another two wish set. So, the process will never end unless, the old man want to stop. The idea is same for linked list. First you have a node where you canimagine thatdatais the first wish and
node*nextis the second wishby which you can create second node just like first. This process will continue until you put NULL in the
*next.Figure: It looks like the old man had lots of wish.ReferencesWikipedia, the free encyclopedia.Pointer in C, from P. Kanetkar.
License
This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)相关文章推荐
- How to create a SharePoint List using Excel 2003(转贴)
- C++ Using recursion to process linked list, 深入理解递归的过程(part1)
- C++ Using recursion to process linked list, 深入理解递归的过程(part2)
- Sound Generator – How to create alien sounds using mathematic formulas
- How to send mail using C++ &amp;amp;amp; CAsyncSocket - SourceCode - 用C++ &amp;amp;amp; CAsyncSocket 如何发送邮件 - 源码 - HackerJLY
- How to get random number within a range using C++ - 如何用C++获取一定范围内的随机数
- How to automate PowerPoint by using Visual C++ 5.0 or Visual C++ 6.0 with The Microsoft Foundation Classes
- how to copy a linkedlist
- How to make a full-screen application using Symbian C++, 怎样在Sysmbian C++中制作全屏应用程序
- How to create a gun c/c++ project
- how to create images using gdal
- How to access database using C++ & ADO - 如何用C++和ADO访问数据库
- How to enable sorting on a GridView using an IEnumerable list as datasource
- 如何反转一个单链表 How to reverse a singly linked list
- How to create MFC applications that do not have a menu bar in Visual C++(MFC单文档和多文档程序中去掉菜单栏)(转)
- How to show a modal dialog and modeless dialog using C++ - 如何用C++显示一个模态对话框和一个非模态对话框
- How to change the background color of form using C++ - 如何用C++改变窗体的颜色
- How to create a resizeable dialog box with scroll bars in Visual C++
- how to create list box example
- How to using eclipse to develpe C/C++