Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stack>
- using namespace std;
- class node{
- protected:
- int element;
- node* link;
- public:
- //constructor that accepts only element
- node(int element) {
- this->element = element;
- this->link = NULL;
- }
- //constructor that accepts both link and element
- node(int element, node* link){
- this->element = element;
- this->link = link;
- }
- //method to update the element
- void updateData(int element){
- this->element = element;
- }
- //method to update or setup link
- void updateLink(node* link){
- this->link = link;
- }
- //method to get the element from the node
- int getElement(){
- return this->element;
- }
- //method to get the next node
- node* getNextNode(){
- return this->link;
- }
- };
- class Linkedlist {
- public:
- node *head;
- //constructor for the Linked List class
- Linkedlist() {
- head = NULL;
- }
- //returns head node
- node *getHead() {
- return this->head;
- }
- // method to add a node at the end
- void insert(int element) {
- node *tempNode = new node(element);
- node *p = head;
- if (head == NULL) {
- head = tempNode;
- return;
- }
- else {
- while (p->getNextNode() != NULL) {
- p = p->getNextNode();
- }
- p->updateLink(tempNode);
- return;
- }
- }
- //method to display all the elements of the Linked List
- void display() {
- cout << "\n";
- node *tempNode = head;
- while (tempNode != NULL) {
- if (tempNode->getNextNode() != NULL)
- cout << tempNode->getElement() << " --> ";
- else
- cout << tempNode->getElement();
- tempNode = tempNode->getNextNode();
- }
- return;
- }
- // deleting node with only that node pointer
- void deleteNode(node* nodePtr){
- if(nodePtr == NULL){
- return;
- }else{
- // make a pointer to next node
- node* nextNode = nodePtr->getNextNode();
- // copy deteils of next node to current node
- nodePtr->updateData(nextNode->getElement());
- nodePtr->updateLink(nextNode->getNextNode());
- // delete next node
- free(nextNode);
- }
- }
- // deleting kth element from the end
- int delete_kth_Element_End(int k){
- node* first = this->getHead();
- node* second = this->getHead();
- for(int i=0; i < k; i++){
- second = second = second->getNextNode();
- }
- while(second != NULL){
- first = first->getNextNode();
- second = second->getNextNode();
- }
- deleteNode(first);
- }
- };
- int main() {
- cout<<"Program to delete kth element from the in a Linked List";
- Linkedlist l1;
- l1.insert(1);
- l1.insert(3);
- l1.insert(5);
- l1.insert(7);
- l1.insert(7);
- l1.insert(8);
- l1.insert(5);
- l1.insert(3);
- l1.insert(1);
- cout<<"\nLinked list is : ";
- l1.display();
- cout<<"\nLinked List after deleting 5th element from the end is : ";
- l1.delete_kth_Element_End(5);
- l1.display();
- return 0;
- }
Add Comment
Please, Sign In to add comment