Skip to content

Instantly share code, notes, and snippets.

@SohanChy
Last active March 14, 2016 06:16
Show Gist options
  • Select an option

  • Save SohanChy/7aced24c2d779d166f1d to your computer and use it in GitHub Desktop.

Select an option

Save SohanChy/7aced24c2d779d166f1d to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
struct ListNode
{
int data;
ListNode *next;
};
ListNode* GetNewNode(int userData = 0,bool userInput = false)
{
ListNode *Node = new ListNode;
if(userInput == true)
{
cin>>Node->data;
}
else
{
Node->data = userData;
}
Node->next = NULL;
return Node;
}
void DeleteNode(ListNode*& Head,int position)
{
ListNode* tmp = Head;
if(position > 0)
{
for(int i=0; i<(position-1) && tmp != NULL; i++)
{
tmp = tmp->next;
}
ListNode* toDelete = tmp->next;
tmp->next = toDelete->next;
delete toDelete;
}
else
{
Head = tmp->next;
delete tmp;
}
}
void printList(ListNode *Head)
{
ListNode *tmp = Head;
cout<<endl;
while(tmp != NULL)
{
cout<<tmp->data<<" ";
tmp = tmp->next;
}
cout<<endl;
}
int SearchNode(ListNode* Head,int needle)
{
ListNode *tmp = Head;
for(int i = 0; tmp != NULL ; i++)
{
if(tmp->data == needle)
{
return i;
}
tmp = tmp->next;
}
return -1;
}
void insertBeg(ListNode*& Head,int value)
{
ListNode* newNode = GetNewNode(value);
newNode->next = Head;
Head = newNode;
}
void insertAfter(ListNode* Head,int afterVal, int value)
{
ListNode * tmp = Head;
bool found = false;
while(tmp != NULL)
{
if(tmp->data == afterVal)
{
ListNode* newNode = GetNewNode(value);
newNode->next = tmp->next;
tmp->next = newNode;
found = true;
}
tmp = tmp->next;
if(found== false && tmp->next == NULL)
{
break;
}
}
if(found == false)
{
ListNode* newNode = GetNewNode(value);
tmp->next = newNode;
}
}
class lStack
{
ListNode *Head;
ListNode *Node;
int maxSize,ssize;
public:
lStack()
{
Head = Node = NULL;
ssize = 0;
maxSize = 5;
}
void push(int x)
{
if(ssize<maxSize)
{
ssize++;
if(Head == NULL)
{
Node = GetNewNode(x,false);
Head = Node;
}
else
{
Node->next = GetNewNode(x,false);
Node = Node->next;
}
ssize++;
}
else cout<<"Overflow"<<endl;
}
void pop()
{
if(Head != NULL)
{
ListNode *tmp = Head;
int i;
for(i = 0; tmp != Node && tmp != NULL; i++)
{
tmp = tmp->next;
}
DeleteNode(Head,i);
tmp = Head;
for(; tmp!=NULL && tmp->next != NULL;)
{
tmp = tmp->next;
}
Node = tmp;
ssize--;
}
else cout<<"Stack underflow"<<endl;
}
int top()
{
return Node->data;
}
};
int main()
{
lStack test;
test.push(3);
cout<<test.top();
test.push(4);
cout<<test.top();
test.push(5);
cout<<test.top();
test.pop();
cout<<test.top();
test.push(5);
test.pop();
cout<<test.top();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment