TECH GUIDE BLOG

Tech Guide Programming Tutorial Tips Tricks

Linear Single Linked List C++

Posted by Admin On March - 26 - 2009

Hey, back to programming again in data structure. It’s now about Linked List, a linear single linked list it’s about to be explained in this post. We can imagine this like a chain, every data has a link to another data. Single Linked List is different from array. In array, we can only insert a new data to the last index after the last data. We can not insert at any place we want. So, the linked list was made.

linear-single-link-list

The Node

At linked list, we add a header, we called it node. This node is used for data to be linked to another data. It’s like each one person has one another person’s address. So, this is the advantage to use linked list instead of array. If a new data want to be placed between another data, we just have to change the address/ node of the data.

linear-single-link-list-add

Insert data

Feel confused? Let’s get to the code. I will make a simple linear single linked list that can insert a data at any index.

//====START====//

#include <stdio.h>
#include <conio.h>
#include <iostream.h>
#include <windows.h>

class node
{
private:
 int data;
 node * next;
public:
 node()
 {
  next=NULL;
 }
  int get()
 {
  return data;
 }
 void set(int x)
 {
  data=x;
 }
 node * nget()
 {
  return (next);
 }
 void nset(node * nextnode)
 {
  next=nextnode;
 }
};

class Link
{
private:
 node * head, * tail;
public:
 Link()
 {
  head=NULL;
  tail=NULL;
 }
 void add(int data)
 {
  node * baru;
  baru=new node;
  baru->set(data);
  if(!head)
  {
   head=baru;
   tail=head;
  }
  else
  {
   tail->nset(baru);
   tail=baru;
  }
 }
 void view()
 {
  node * temp;
  temp=head;
  if(temp)
  {
   while(temp)
   {
    printf("%d",temp->get());
    temp=temp->nget();
   }
  }
 }
 void addmid(int index,int data)
 {
  int i=0;
  node *temp,*ndata;
  temp=head;
  ndata=new node;
  ndata->set(data);
  while(i<index)
  {
   temp=temp->nget();
   i++;
  }
  ndata->nset(temp->nget());
  temp->nset(ndata);
 }

};

//====END====//

It’s done. You can start to implement this code in your main cpp.

Popularity: 38% [?]

Share and Enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • Blogplay
  • MySpace
  • StumbleUpon
  • Suggest to Techmeme via Twitter
  • Technorati
  • Twitter

Leave a Reply