Skip to content

Instantly share code, notes, and snippets.

@mogutou1214
Last active December 23, 2015 11:38
Show Gist options
  • Save mogutou1214/6629447 to your computer and use it in GitHub Desktop.
Save mogutou1214/6629447 to your computer and use it in GitHub Desktop.
C++ Linked list
// Linkedlist.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
class linkedList{
private:
node *head;
public:
linkedList(){
head = NULL;
};
node *newNode(int val){
node *n = new node;
n->data = val;
n->next = NULL;
return n;
};
void createList(int a[], int length){
if(head==NULL)
head = newNode(a[0]);
node *curr = head;
for(int i=1;i<length;i++){
node *n = newNode(a[i]);
curr->next = n;
curr = n;
}
};
void printAll(){
node *curr = head;
while(curr!=NULL){
cout << curr->data << " ";
curr = curr->next;
}
};
int length(){
node *curr=head;
int count = 0;
while(curr!=NULL){
++count;
curr=curr->next;
}
return count;
};
void addFront(int val){
node *n = newNode(val);
n->next = head;
head = n;
}
void addTail(int val){
node *curr = head;
if(head==NULL)
head = newNode(val);
else{
while(curr->next!=NULL)
curr=curr->next;
node *n = newNode(val);
curr->next = n;
}
};
};
int _tmain(int argc, _TCHAR* argv[])
{
linkedList ll;
int a[] = {1,2,3,4,7};
ll.createList(a,5);
ll.addFront(9);
ll.addTail(100);
ll.printAll();
char letter;
cin >> letter;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment