-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodedelete.cp
94 lines (77 loc) · 1.88 KB
/
nodedelete.cp
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
using System;
// This class represents a single node
// in a linked list
class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
// This is a utility class for linked list
class LLUtil
{
// This function creates a linked list
// from a given array and returns head
public Node createLL(int[] arr)
{
Node head = new Node(arr[0]);
Node temp = head;
Node newNode = null;
for(int i = 1; i < arr.Length; i++)
{
newNode = new Node(arr[i]);
temp.next = newNode;
temp = temp.next;
}
return head;
}
// This function prints given linked list
public void printLL(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
Console.WriteLine();
}
}
class GFG{
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 12, 15, 10, 11, 5, 6, 2, 3 };
LLUtil llu = new LLUtil();
Node head = llu.createLL(arr);
Console.WriteLine("Given Linked List");
llu.printLL(head);
deleteNodesOnRightSide(head);
Console.WriteLine("Modified Linked List");
llu.printLL(head);
}
// Main function
public static void deleteNodesOnRightSide(Node head)
{
Node temp = head;
while (temp != null && temp.next != null)
{
// Copying next node data into current node
// i.e. we are indirectly deleting current node
if (temp.data < temp.next.data)
{
temp.data = temp.next.data;
temp.next = temp.next.next;
}
else
{
// Move to the next node
temp = temp.next;
}
}
}
}
// This code is contributed by rutvik_56