-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
SinglyLinkedList.cpp
76 lines (68 loc) · 1.29 KB
/
SinglyLinkedList.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*A simple C++ program for singly linked list*/
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node(int value){
data=value;
next=NULL;
}
};
Node* takeInput(){
//size of the linked list
int size;
cin>>size;
//head and tail of the linked list intialised to NULL
Node* head=NULL;
Node* tail=NULL;
while(size--){
//value to be inserted
int num;
cin>>num;
//creation of new node
Node* newNode=new Node(num);
//if there are no previous elements in the linked list
if(head==NULL) head=tail=newNode;
else{
//else add the new node to the end of the tail
//and make it tail
tail->next=newNode;
tail=newNode;
}
}
return head;
}
void PrintLL(Node* head){
Node* ptr=head;
//transverse until it reaches the end node (NULL)
while(ptr!=NULL){
cout<<ptr->data<<" ";
ptr=ptr->next;
}
cout<<endl;
}
Node* middleElement(Node* head) {
Node* slowPtr = head;
Node* fastPtr = head;
while(fastPtr != nullptr && fastPtr->next != nullptr) {
slowPtr = slowPtr->next;
fastPtr = fastPtr->next->next;
}
return slowPtr;
}
int main(){
//create the linked list
Node* head=takeInput();
//print the linked list
PrintLL(head);
return 0;
}
//Test case
/*Input Example
Input:
5
10 20 30 40 50
Output:
10 20 30 40 50*/