1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
|
#include <iostream>
using namespace std;
// A simple struct for node
struct Node{
int data;
Node* next;
};
void print(Node* &);
void Insert_Beginning(Node* &, int);
void Insert_End(Node* &, int);
void Insert_At_n(Node* &, int, int);
void Delete_At_n(Node* &, int);
int main()
{
Node* pToHead;
pToHead = 0; // pointer to head node set to null for now;
cout << "How many numbers? ";
int n;
cin >> n;
int x;
// this loop is intended to create 2n Nodes with int data.
for(int i = 1; i<=n; i++)
{
cout << "\nEnter number: ";
cin >> x;
Insert_Beginning(pToHead, x);
//Insert_End(pToHead, x);
print(pToHead);
}
Insert_At_n(pToHead, 100, 1);
print(pToHead);
Insert_At_n(pToHead, 200, 2);
print(pToHead);
Insert_At_n(pToHead, 300, 3);
print(pToHead);
Insert_At_n(pToHead, 800, 2);
print(pToHead);
Delete_At_n(pToHead, 2);
print(pToHead);
Delete_At_n(pToHead, 4);
print(pToHead);
Delete_At_n(pToHead, 1);
print(pToHead);
return 0;
}
void Insert_Beginning(Node* &pToHead, int x)
{
Node* temp = new Node;
temp->data = x;
temp->next = pToHead;
pToHead = temp;
}
void Insert_End(Node* &pToHead, int x)
{
Node* temp = new Node;
Node* temp1;
temp->next = 0;
temp->data = x;
if(pToHead == 0)
pToHead = temp;
else
{
temp1 = pToHead;
while(temp1->next != 0)
{
temp1 = temp1->next;
}
temp1->next = temp;
}
}
// insert int data at position n
void Insert_At_n(Node* &pToHead, int data, int n)
{
Node* temp = new Node;
Node* temp1;
temp->data = data;
temp->next = 0;
if(n == 1)
{
temp->next = pToHead; // set link field of new node to whatever pToHead was linked to
pToHead = temp; // point pToHead to new node
return;
}
temp1 = pToHead;
for(int i=0; i<n-2; i++) // go to n-1th nodel
{
temp1 = temp1->next;
}
temp->next = temp1->next; // set link field of new node to whatever n-1th node was pointing to
temp1->next = temp; // link n-1th node to new node
}
void Delete_At_n(Node* &pToHead, int n)
{
if(pToHead == 0)
return;
Node* temp = pToHead;
if(n==1) // special case for deleting first node;
{
pToHead = temp->next; // point pToHead to wherever first node was linked to
return;
}
for(int i=0; i<n-2; i++) // go to n-1th node
{
temp = temp->next;
}
temp->next = temp->next->next; // point n-1th node to whatever nth node is pointing to
return;
}
void print(Node* &pToHead)
{
cout << "The list is: ";
for(Node* temp = pToHead; temp != 0; temp = temp->next)
cout << temp->data << " ";
cout << "\n";
}
|