-
Notifications
You must be signed in to change notification settings - Fork 2
/
truncate_linkedlist.cpp
61 lines (53 loc) · 1.01 KB
/
truncate_linkedlist.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
51
52
53
54
55
56
57
58
59
60
61
#include <iostream>
using namespace std;
class node{
public:
int data;
node* next;
};
void push(node** h_ref,int data ){
node * new_node = new node();
new_node->data = data;
new_node->next = *h_ref;
*h_ref = new_node;
}
void print(node* head){
while(head){
cout<<head->data<<"->";
head=head->next;
}
}
node* truncate(node* head,int pos)
{
node* temp = head;
node* new_node;
for(int i=1;i<pos;i++)
{
temp = temp->next;
}
new_node = temp->next;
temp->next = NULL;
return new_node;
}
int main()
{
node* head= NULL;
node* head2= NULL;
push(&head,3);
push(&head,2);
push(&head,5);
push(&head,6);
push(&head,7);
push(&head,8);
push(&head,4);
cout<<"before truncate"<<endl;
print(head);
cout<<endl;
node* head3 = truncate(head,3);
cout<<"after truncate original"<<endl;
print(head);
cout<<endl;
cout<<"after truncate new"<<endl;
print(head3);
return 0;
}