-
Notifications
You must be signed in to change notification settings - Fork 0
/
17_DeleteNode.cpp
50 lines (44 loc) · 900 Bytes
/
17_DeleteNode.cpp
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
// https://practice.geeksforgeeks.org/problems/delete-node-in-doubly-linked-list
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next;
struct Node *prev;
Node(int x)
{
data = x;
next = NULL;
prev = NULL;
}
};
class Solution
{
public:
Node *deleteNode(Node *head_ref, int x)
{
if (!head_ref) return head_ref;
Node *p = head_ref, *prev = nullptr;
while(--x){
prev = p;
p = p->next;
}
if (!prev){
head_ref = head_ref->next;
if (head_ref) head_ref->prev = nullptr;
}
else {
prev->next = p->next;
if (p->next) p->next->prev = prev;
}
delete(p);
return head_ref;
}
};
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}