Created
February 14, 2014 07:50
-
-
Save frank4565/8997270 to your computer and use it in GitHub Desktop.
2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
This file contains hidden or 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
#include<iostream> | |
using namespace std; | |
struct Node | |
{ | |
int data; | |
Node *next; | |
Node(int data, Node *next) { | |
this->data = data; | |
this->next = next; | |
} | |
~Node() {} | |
}; | |
typedef Node* pNode; | |
void delNode(pNode p) | |
{ | |
if (p == nullptr || p->next == nullptr) return; | |
pNode t = p->next; | |
p->data = t->data; | |
p->next = t->next; | |
delete t; | |
} | |
void print(Node * head) | |
{ | |
while (head != nullptr) { | |
cout << head->data << " "; | |
head = head->next; | |
} | |
cout << endl; | |
} | |
void clear(Node *head) | |
{ | |
if (head != nullptr) { | |
while(head->next != nullptr) { | |
Node *t = head->next; | |
head->next = t->next; | |
delete t; | |
} | |
delete head; | |
} | |
} | |
int main(int argc, char *argv[]) | |
{ | |
Node *list = new Node(0, new Node(1, new Node (2, new Node(3, new Node(4, nullptr))))); | |
print(list); | |
delNode(list->next->next->next); | |
print(list); | |
clear(list); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment