//
// main.cpp
// Delete from Linked List
//
// Created by Himanshu on 15/09/21.
//
#include <iostream>
using namespace std;
struct node {
int info = 0;
struct node *next;
};
typedef struct node Node;
node* newNode(int data)
{
node* Node = new node();
Node->info = data;
Node->next = NULL;
return(Node);
}
void printLinkedList (Node* head) {
Node *x = head;
while (x != NULL) {
cout<<(x->info)<<" ";
x = x->next;
}
cout<<endl;
}
Node* insertNode (Node *head, Node* x) {
x->next = head;
head = x;
return head;
}
void deleteNode (Node* x) {
if (x == NULL) {
return;
} else if (x->next == NULL) {
cout<<"Last node can't be deleted without head pointer"<<endl;
return;
}
Node* temp = x->next;
x->info = temp->info;
x->next = temp->next;
delete (temp);
}
int main(int argc, const char * argv[]) {
Node *head = newNode(7);
head = insertNode (head, newNode(6));
head = insertNode (head, newNode(5));
head = insertNode (head, newNode(4));
head = insertNode (head, newNode(3));
head = insertNode (head, newNode(2));
head = insertNode (head, newNode(1));
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Deleting Node 1"<<endl;
deleteNode(head);
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Deleting Node 4"<<endl;
deleteNode(head->next->next);
cout<<"Linked List:"<<endl;
printLinkedList(head);
cout<<"Deleting Node 7"<<endl;
deleteNode(head->next->next->next->next);
cout<<"Linked List:"<<endl;
printLinkedList(head);
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBEZWxldGUgZnJvbSBMaW5rZWQgTGlzdAovLwovLyAgQ3JlYXRlZCBieSBIaW1hbnNodSBvbiAxNS8wOS8yMS4KLy8KCiNpbmNsdWRlIDxpb3N0cmVhbT4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnN0cnVjdCBub2RlIHsKICAgIGludCBpbmZvID0gMDsKICAgIHN0cnVjdCBub2RlICpuZXh0Owp9Owp0eXBlZGVmIHN0cnVjdCBub2RlIE5vZGU7Cgpub2RlKiBuZXdOb2RlKGludCBkYXRhKQp7CiAgICBub2RlKiBOb2RlID0gbmV3IG5v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