Created
September 19, 2013 21:36
-
-
Save mogutou1214/6630197 to your computer and use it in GitHub Desktop.
C++ Linked list-generic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Linkedlist.cpp : Defines the entry point for the console application. | |
// | |
#include "stdafx.h" | |
#include <iostream> | |
using namespace std; | |
template <class T> | |
struct node{ | |
T data; | |
node *next; | |
}; | |
template <class T> | |
class linkedList{ | |
private: | |
node<T> *head; | |
public: | |
linkedList(){ | |
head = NULL; | |
}; | |
node<T> *newNode(T val){ | |
node<T> *n = new node<T>; | |
n->data = val; | |
n->next = NULL; | |
return n; | |
}; | |
void createList(T a[], int length){ | |
if(head==NULL) | |
head = newNode(a[0]); | |
node<T> *curr = head; | |
for(int i=1;i<length;i++){ | |
node<T> *n = newNode(a[i]); | |
curr->next = n; | |
curr = n; | |
} | |
}; | |
void printAll(){ | |
node<T> *curr = head; | |
while(curr!=NULL){ | |
cout << curr->data << " "; | |
curr = curr->next; | |
} | |
}; | |
int length(){ | |
node<T> *curr=head; | |
int count = 0; | |
while(curr!=NULL){ | |
++count; | |
curr=curr->next; | |
} | |
return count; | |
}; | |
void addFront(T val){ | |
node<T> *n = newNode(val); | |
n->next = head; | |
head = n; | |
} | |
void addTail(T val){ | |
node<T> *curr = head; | |
if(head==NULL) | |
head = newNode(val); | |
else{ | |
while(curr->next!=NULL) | |
curr=curr->next; | |
node<T> *n = newNode(val); | |
curr->next = n; | |
} | |
}; | |
}; | |
int _tmain(int argc, _TCHAR* argv[]) | |
{ | |
linkedList<int> ll; | |
int a[] = {1,2,3,4,90}; | |
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