Linked list in Java - 72: Rearrange a linked list in zig-zag manner
Vložit
- čas přidán 3. 11. 2019
- Source Code: thecodingsimplified.com/rearr...
Solution:
- Take a boolean variable flag
- Now, iterate from 1st node of list & check if element is less than next element
- Same way, in next iteration check if it's greater than next element
- In both condition, if condition matches, swap the values
- At last, we'll have arranged value
- Time Complexity: O(n) for iterating the n elements of linked list
- Space Complexity: O(1) as we're taking only constant variables
Please check video for more info:
This problem is similar to:
how to do rearrange a linked list in zig zag manner,
arrange a linked list in zig zag manner,
linked list in zig zag manner,
linked list,
zig zag,
zig-zag,
arrange,
tutorial,
coding simplified,
java
CHECK OUT CODING SIMPLIFIED
/ codingsimplified
I started my CZcams channel, Coding Simplified, during Dec of 2015.
Since then, I've published over 300+ videos. My account is Partner Verified.
★☆★ VIEW THE BLOG POST: ★☆★
thecodingsimplified.com
★☆★ SUBSCRIBE TO ME ON CZcams: ★☆★
czcams.com/users/codingsimplif...
★☆★ SEND EMAIL At: ★☆★
Email: thecodingsimplified@gmail.com
thank you sir! only your explanation was enough :)
Thanks for your nice feedback. Keep Watching.
thank you sir
Node *zigZag(Node* head)
{
// your code goes here
if(head == NULL || head->next == NULL){
return head;
}
Node* node = head;
bool flag=true;
while(node != NULL && node->next != NULL){ // if I am running without this node->next != NULL its giving segmentation fault , I don't know how the code in video is working but if we are at last node then the NULL->data will not be there and it will give runtime seg. error
if(flag){
if(node->data > node->next->data){
swap(node->data, node->next->data);
}
flag = !flag;
}
else{
if(node->data < node->next->data){
swap(node->data , node->next->data);
}
flag = !flag;
}
node = node->next;
}
return head;
}