Delete the mid node

/***
Implement an algorithm to delete a node in the middle of a singly linked list given only access to that node.
EXAMPLE
Input: the node c from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a->b->d->e
***/
//if the number of nodes is even, how to deal with the middle of the list?
/**
IDEA: copy the val of the next node to the current node and delete the next
**/

#include<iostream>

using namespace std;

struct node {
int val;
node *next;
};

/*
void deleteMiddle(node *n) {
node *p;
int count = 0;
int mid;
p = n;

//count the list
while(p != nullptr) {
count++;
p = p->next;
}

p = n;
//remove the mid
mid = count / 2;
int i = 1;
while (i != mid) {
p = p->next;
i++;
}
if(count % 2 == 0) {
p->next = p->next->next->next;
} else {
p->next = p->next->next;
}
} */

void deleteMid(node *n) {
n->val = n->next->val;
 node *t = n->next;
n->next = t->next;
 delete t;
}

void main() {
node n1, n2, n3, n4, n5, n6;
n1.val = 1;
n1.next = &n2;
n2.val = 2;
n2.next = &n3;
n3.val = 1;
n3.next = &n4;
n4.val = 3;
n4.next = &n5;
n5.val = 2;
n5.next = &n6;
n6.val = 6;
n6.next = nullptr;


deleteMid(&n3);

node *p1;
p1 = &n1;
while (p1 != nullptr)
{
cout<<p1->val<<"  ";
p1 = p1->next;
}
}

Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs