Introduction to Linked Lists (Data Structures & Algorithms #5)

  Рет қаралды 994,292

CS Dojo

CS Dojo

Күн бұрын

Learn the basics of linked lists. Java & Python sample code below.
Check out Brilliant.org (brilliant.org/..., a website for learning math and computer science concepts through solving problems. First 200 subscribers will get 20% off through the link above.
Special thanks to Brilliant for sponsoring this video.
Find sample code in Python and Java here: www.csdojo.io/...
This was #5 of my data structures & algorithms series. You can find the entire series in a playlist here: goo.gl/wy3CWF
Also, keep in touch on Facebook: / entercsdojo

Пікірлер: 1 000
@CSDojo
@CSDojo 6 жыл бұрын
Hey everyone! If you are looking for more practice problems for arrays and linked lists, I’d also recommend my Udemy course, “11 Essential Coding Interview Questions” here: goo.gl/v35LCa It’s supposed to be for programming interview questions, but it should be a good resource for improving your problem-solving skills in general. Anyway, thanks as always for watching! If you don’t want to pay for the course, remember that I have a ton of other free videos right here on this KZbin channel :)
@technicalilm8999
@technicalilm8999 6 жыл бұрын
make a video on hash tables and hashing please
@astonchui808
@astonchui808 6 жыл бұрын
Thank you very much for another good quality lesson! Please consider making a complete computer science course! Even on Udemy, very interested to buy it!
@benshkabanka9044
@benshkabanka9044 6 жыл бұрын
CS Dojo hey there! I like your videos and would like to ask you something, so here goes: "How do you learn something new, so that you don't forget it sometime soon?" Because I often find myself forgetting stuff that I have just learned a few days or weeks ago. For example I learn about lists, maps and dictionaries. Then a few days later I want to realize a Programm and start cracking my head what I should use and how it worked. Then I have to Google again and look it up. I have this kind of problem for many things except the absolute basics. How did you Crack everything in your head so you don't forget it again?
@nadavhacmun2560
@nadavhacmun2560 6 жыл бұрын
i had the exact same solution like you and now i'm happy :)
@No1lolizone
@No1lolizone 6 жыл бұрын
Thanks bro. You are providing us a very great and simple knowledge about programming. Keep going.
@davidemilan59
@davidemilan59 4 жыл бұрын
When a KZbin video teaches you better than your programming professor at University lol
@TheJoaohc
@TheJoaohc 4 жыл бұрын
Exactly!
@zclee7325
@zclee7325 3 жыл бұрын
it always to be like that
@ahiduzzamanahir1338
@ahiduzzamanahir1338 3 жыл бұрын
@Xiogenes You're paying money for the syllabus....lol
@ysheepy4907
@ysheepy4907 3 жыл бұрын
Cant agree more. My professor explains it so terribly that my brain went spaghetti ...
@realnice3672
@realnice3672 3 жыл бұрын
@@ysheepy4907 tasty lol
@Artouple
@Artouple 3 жыл бұрын
My solution, writing before watching the solution: int countNodes(Node head){ var count = 1; //As head is not null while(head.next.data != null){ count++; head = head.next; } return count; }
@balajiramadoss6014
@balajiramadoss6014 8 күн бұрын
header.next.data will throw null pointer exception if header.next is null
@damiajayi2081
@damiajayi2081 4 жыл бұрын
Really proud of myself for doing this without looking at any hints. I don't get a lot of exercise questions. I love your method of teaching My Java Code: public class LinkedList { public static void main(String[] args) { Node head = new Node(6); Node nodeB = new Node(5); Node nodeC = new Node(5); Node nodeD = new Node(5); Node nodeE = new Node(5); head.next = nodeB; nodeB.next = nodeC; nodeC.next = nodeD; nodeD.next = nodeE; System.out.println(countNodes(head)); } static int countNodes(Node head){ int count = 1; Node current = head; while(current.next != null){ count++; current = current.next; } return count; } }
@Michael-f8x4h
@Michael-f8x4h 11 ай бұрын
it doesn't run tho
@tpsspace7397
@tpsspace7397 8 ай бұрын
@@Michael-f8x4h his code is fine
@zeno5053
@zeno5053 3 жыл бұрын
12:04 a three-line solution from python def countNodes(head, count = 1): if head.next != None: return countNodes(head.next, count + 1) return count
@zydiz
@zydiz 2 жыл бұрын
a great solution but butting the "if" expression in the same line with the statement doesn't actually reduce a line.
@codekarlebhai
@codekarlebhai Жыл бұрын
@@zydiz its not if, its ternary operator with combination of recursion(but yeh logic is same)
@balajiramadoss6014
@balajiramadoss6014 8 күн бұрын
fcuk your 3 lines or 2 lines. you must say that you are using recursion instead of iteration. that's it. nothing impressive from this code
@tomseinfeld7124
@tomseinfeld7124 5 жыл бұрын
In JavaScript function countNode(node) { let totalNodes = 1; let myNode = node; while(myNode.next) { total++; myNode = myNode.next; } return totalNodes; }
@sourabhkumar3852
@sourabhkumar3852 3 жыл бұрын
inside while loop it will be totalNodes++ . Rest everything is absolutely correct.
@The_Bruh_26
@The_Bruh_26 25 күн бұрын
For this to work the totalNodes must be set to 0 or myNode and totalNodes operations inside the while loop should be switched, as head is being counted twice in this example
@vivek3861
@vivek3861 6 жыл бұрын
Best and simplest teaching ever...thanks.
@waelassaf4740
@waelassaf4740 5 жыл бұрын
Bless Up.
@heavysaber9431
@heavysaber9431 4 жыл бұрын
I wish I learned programming at high school, all I did was play video games...
@aryanshmahato
@aryanshmahato 4 жыл бұрын
@@heavysaber9431 I feel lucky now
@heavysaber9431
@heavysaber9431 4 жыл бұрын
@@aryanshmahato I envy you brother, dedicate that time to programming!
@shadowagent3
@shadowagent3 4 жыл бұрын
divide by 2 each time and pick higher / lower half. its ez
@ivanrsbr
@ivanrsbr 5 жыл бұрын
Excellent videos, thank you for this great tutorial. My solution in Java is to add the following function to the Node class: int countNodes() { if (this.next == null) return 1; else return this.next.countNodes()+1; } This will recursively search for child nodes and return the count.
@ArmandoAlejandro2014
@ArmandoAlejandro2014 5 жыл бұрын
I've been a developer for 25 yrs and i got 2 weeks to prepare for a Google technical interview and I'm relying on your videos to help me prepare. I have to relearn alot of stuff I haven't used in years. You have to go into teaching. America's kids need somebody that can teach as well as you. Thanks kid.
@muwongenicholas6281
@muwongenicholas6281 3 жыл бұрын
did you get the job?
@DanNjeru1
@DanNjeru1 3 жыл бұрын
Don't leave us hanging Armando. It's been two years.
@snoudoubts1745
@snoudoubts1745 3 жыл бұрын
Armando now works for the Government of Texas ;)
@webknowledge9989
@webknowledge9989 2 жыл бұрын
@@snoudoubts1745 how u know?
@eliadaballazhi2982
@eliadaballazhi2982 2 жыл бұрын
@@DanNjeru1 hahahaahahah dead
@satan9487
@satan9487 5 жыл бұрын
I was struggling with this for ages! Thank you a lot
@emmettanderson9185
@emmettanderson9185 6 жыл бұрын
YK your amazing I love that you quit your high paying job at google to teach on KZbin I hope your channel blows up and you become famous!
@UnrecycleRubdish
@UnrecycleRubdish 4 жыл бұрын
looks like your wish became true. he has more than a million followers in 2020 =)
@realnice3672
@realnice3672 3 жыл бұрын
@@UnrecycleRubdish yeah lol
@acidtears
@acidtears 4 жыл бұрын
You're the Khanacademy of programming! Love this series and your step-by-step explanations.
@suyashsharma7088
@suyashsharma7088 5 жыл бұрын
You have the best explanation of all the KZbin tutorials out there! Keep up with the good work. I had so much trouble understanding and learning Linked List. If I would have had watched your videos earlier, it would have had definitely made my struggle period shorter. Thank you very much and keep up with the good work. :D
@heidik1757
@heidik1757 4 жыл бұрын
You're an incredible teacher. Hope these videos never end and stretch across even the most advanced of topics. Very enjoyable.
@highmaths7698
@highmaths7698 6 жыл бұрын
You're doing a great job CS. I have already recommended your channel to a dozen friends. Keep up the good work!
@MesitaButClean
@MesitaButClean Жыл бұрын
best video i ever see about linked list, my teacher explained TWO weeks and THIS MAN EXPLAINS IT IN 18 MINUTES, AND IM STUDYING C++!!!
@ananshnawang2360
@ananshnawang2360 2 жыл бұрын
My code for c++: int sizeof_list(){ Node* ptr = head; int count = 0; while( ptr != NULL ){ ptr = ptr->next; count++; } return count; } This code has no parameters since its assumed that this function is specific to object and has access to private members of class.
@aglovecraft
@aglovecraft 5 жыл бұрын
Did it recursively: int countNodes(Node head) { if (head.next == null) { return 1;} else {return 1 + countNodes(head.next);}
@leelakrishna5815
@leelakrishna5815 5 жыл бұрын
at the last node, when the head reaches its end, and there are no other nodes, your count will just return 1.
@nathanunderwood6920
@nathanunderwood6920 5 жыл бұрын
if you have a single line statement screw the skwigglies if(head.next==null) return 1;
@kyosena113
@kyosena113 5 жыл бұрын
@@leelakrishna5815 ..plus 1 for every node before it. It checks out.
@zalavatari8416
@zalavatari8416 4 жыл бұрын
.
@scoutiano4441
@scoutiano4441 4 жыл бұрын
why would you do it recursively if you can do it using a while loop in a few lines?
@citec123x
@citec123x 3 жыл бұрын
You're just amazing, what I like the most is, you just go straight to the point with very clear examples and NO MUMBO JUMBO...!!! An old timer Cobol programmer from last century... *lol*
@nimmiverma1565
@nimmiverma1565 5 жыл бұрын
int countNode(Node head){ int count = 1; Node temp = head; while(temp.next != NULL){ count++; temp = temp.next; } return count; }
@dungletien4676
@dungletien4676 5 жыл бұрын
So how do you solve that problem in the case with 1 Node
@buzzikea
@buzzikea 4 жыл бұрын
@@dungletien4676 if there is only 1 Node, temp.next will always be null, so while loop never executed,hence returned 1
@ericnarciso9156
@ericnarciso9156 3 жыл бұрын
Python recursive count: def count_nodes(head, c=0): if head: c += 1 return count_nodes(head.next, c) return c
@tailcatch5704
@tailcatch5704 4 жыл бұрын
I learned in 20 minutes what my teachers were trying to teach me for 2 hours...
@suman-majhi
@suman-majhi 3 жыл бұрын
my teacher trying to teach me this for last 2 years😂😂
@biqbicle4982
@biqbicle4982 Жыл бұрын
@@suman-majhi nah fundamentals shouldnt go for 2 years your teacher brain damaged
@kyrinky
@kyrinky 6 жыл бұрын
I like the fact that he uses visual examples and actual code to explain the concepts. Most of the time books only have visual examples, and I would understand them, but once it came down to coding it I would just blank out.
@HungNguyen-oz1jc
@HungNguyen-oz1jc 6 жыл бұрын
Can you please next one do using LinkedList for Stack and Queue?
@HungNguyen-oz1jc
@HungNguyen-oz1jc 3 жыл бұрын
@B0bby that’s ok, I already graduated 😂
@ericlansher6101
@ericlansher6101 3 жыл бұрын
@@HungNguyen-oz1jc 🤣
@zaurs0
@zaurs0 2 жыл бұрын
Hi, i used Recursion int countNode(Node head){ System.out.println(head.data); nodeCounter++; if(head.next != null) return countNode(head.next); else return nodeCounter; } i think it works :3
@hamiltonkahonde7939
@hamiltonkahonde7939 5 жыл бұрын
I love this dude!!! He explains this sooo damn well
@MitraNami
@MitraNami 3 жыл бұрын
It was a great video! Thnx Go Python!# Recursion def count_nodes(head): current = head if current.next == None: return 1 return 1 + count_nodes(current.next)
@yiyingzhang9585
@yiyingzhang9585 5 жыл бұрын
def countNodes(head): count = 0 node = head while node.next != null: count +=1 node = node.next return count
@arjunsingh6264
@arjunsingh6264 5 жыл бұрын
Hello! I'm new to the coding scene, and am mostly self taught. I was working with Data Structures but most of my test cases would time out from being too long, and so I tried learning more about Linked Lists but I'm having some trouble with the syntax for Python. You obviously are familiar with it, could you please suggest some tutorials or material I could get a basic idea from? I'd really appreciate it, Thanks!
@coddude3284
@coddude3284 Жыл бұрын
static int countNode(Node head) { int c = 1; // head is node 1 Node nextNode = null; while(head.next != null) { nextNode = head.next ; // i know pffff head = nextNode ; c = c + 1; } return c; }
@patrickmayer9218
@patrickmayer9218 Жыл бұрын
*Think of arrays as one box with many partitions, whereas a linked list is many boxes tethered together. *Head = first node, *Linked lists can be represented in one direction (singly LL) or both (doubly LL) Great video, thanks for the clear explanation!
@finncollins5696
@finncollins5696 Жыл бұрын
only think i consider is your blasphemous image. try to be educated and ethical as a computer science student. Christ the king image has changed and it's so blasphemous.....
@patrickmayer9218
@patrickmayer9218 Жыл бұрын
@@finncollins5696 Dude, I'm a born-again Baptist Christian. I'm not mocking Jesus, it's just a meme.
@Zero-bg2vr
@Zero-bg2vr 5 жыл бұрын
static int countNodes(LinkNode head){ int lengthTracker = 0; // COMMENT 1 SEE BELOW while (head!= null){ // COMMENT 2 SEE BELOW head = head.next; lengthTracker++; } System.out.println(lengthTracker); return lengthTracker; } I'll make this as simple as possible based on how i understood it: Comment 1: The variable "lengthTracker" keeps track of the length. Comment 2: We can assume that we don't know the length of the linked list hence why were using a while loop. Basically we're checking whether the parameter value which is ""LinkNode head" is null or not. If it the head is not null we will move to the next node making it the new head and increment (increase) the lengthTracker variable (lengthTracker++). Now when the while loop runs again it will check whether or not the new value is null or not. If the new head is null then it will quit the while loop, print lengthTracker and return it. Hope that clarify's stuff.
@codingwithsam9194
@codingwithsam9194 6 жыл бұрын
hey sir. a 12 year old boy is inspired by you
@mryup6100
@mryup6100 4 жыл бұрын
Keep it up!
@scum3112
@scum3112 4 жыл бұрын
Are you still coding? I wish I started as early as you. I was only interested in games (although I still love games) kudos to u kid
@II_xD_II
@II_xD_II 4 жыл бұрын
im 13 :D
@pratapkumarsahu8717
@pratapkumarsahu8717 3 жыл бұрын
Me too
@Nicolas-L-F
@Nicolas-L-F 3 жыл бұрын
16 here, keep it up man
@thereaper489
@thereaper489 Жыл бұрын
class Node(): def __init__(self, data=None): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None def append(self, data): #add something to the next node in the list new_node = Node(data) if not self.head: self.head = new_node return current_node = self.head while current_node.next: current_node = current_node.next current_node.next = new_node def prepend(self, data): #add something to the beginning of the list new_node = Node(data) new_node.next = self.head self.head = new_node def print_list(self): #prints the stupid list current_node = self.head while current_node: print(current_node.data) current_node = current_node.next my_list = LinkedList() my_list.append(1) my_list.append(2) my_list.append(3) my_list.prepend(0) my_list.print_list()
@randomorigami6416
@randomorigami6416 3 жыл бұрын
My code for java: static int countNodes(Node head){ int i = 1; while (head.next != null){ i++; head = head.next; } return i; } Node-object is defined as in the video. For the sake of understandability, it could make sense to add a 'cursor' variable like: Node cursor = head before the while-loop, since it is not really the head you are using for the rest. *Like done in the video with current.
@psionicxxx
@psionicxxx Жыл бұрын
You can simplify the while statemet to: while (head.next) { ... It will loop while the statement in parentheses is True. Null is always False when using in conditional statements, thus as long as there's something in head.next, it will report it as True.
@programwithviggo2197
@programwithviggo2197 Жыл бұрын
@@psionicxxx In Java that's gonna give you an error. Null doesn't evaluate to false and an object that isn't null doesn't evaluate to true.
@himanshuupreti9457
@himanshuupreti9457 4 жыл бұрын
Nicely explained, can you please show this class, linkedlist in memory as you did for video of array inside memory... That was fun to know what's inside..
@blue-hydra
@blue-hydra Жыл бұрын
Node current = head; int count = 0; int countNodes(head){ while (current!= null){ current= current.next; count++; } return count; }
@varmarocks009
@varmarocks009 5 жыл бұрын
def count_nodes(linked_list): count_nodes = 0 while linked_list is not None: count_nodes +=1 linked_list = linked_list.next return (count_nodes)
@tanbirmahmud3101
@tanbirmahmud3101 4 жыл бұрын
Thx
@picumtg5631
@picumtg5631 4 жыл бұрын
exactly same solution. Now io dont feel stupid
@NripendraPatwa
@NripendraPatwa 3 жыл бұрын
My code in python for 11:47 def countNodes(head): temp = 0 list1 = [4, 2, 3, 10, 2] head = (list1[0]) if print(head) for x in list1: x = 1 temp += x return(temp) print(head) My computer shows this function is wrong, but I don't understand what. Please tell me (also thank you because I am just a starting beginner and your python for absolute beginners series was a ginormous help)
@TorIvanBoine
@TorIvanBoine 6 жыл бұрын
This is cool and all. But what is the practical use of linked lists? Easier to understand the concept if we know what its used for.
@clebersonfrodriguesjunior2060
@clebersonfrodriguesjunior2060 6 жыл бұрын
dynamic allocation in memory, i guess. items of same collection can be stored in different locations of memory...
@delaghetto0
@delaghetto0 5 жыл бұрын
kzbin.info/www/bejne/lZu0mXSCfpmooMk
@GurpreetSingh-et8ix
@GurpreetSingh-et8ix 5 жыл бұрын
One of the most widely used data types in computing is hash tables. If you would like to create one from scratch, linked lists are the easiest way to implement them. First learn how to implement a linked list from scratch and then learn how to use that to create a hash table.
@technicalilm8999
@technicalilm8999 6 жыл бұрын
python implementation ::: def countNodes(head): if head.Next != None: countNodes.count += 1 ConsecutiveNode = head.Next countNodes(ConsecutiveNode) return countNodes.count class Node: def __init__(self,data): self.data = data self.Next = None head = Node(4) nodeB = Node(2) nodeC = Node(3) nodeD = Node(10) nodeE = Node(34) countNodes.count = 1 # Assuming head is not null head.Next = nodeB nodeB.Next = nodeC nodeC.Next = nodeD nodeD.Next = nodeE print(countNodes(head))
@adityamandal8604
@adityamandal8604 6 жыл бұрын
what should it really print?
@technicalilm8999
@technicalilm8999 6 жыл бұрын
Aditya Mandal no of nodes
@adityamandal8604
@adityamandal8604 6 жыл бұрын
It prints out 1
@technicalilm8999
@technicalilm8999 6 жыл бұрын
Aditya Mandal there might be problem with the indentation while copying and pasting
@mesta5539
@mesta5539 6 жыл бұрын
replace the if with a while
@SMAOS1
@SMAOS1 Жыл бұрын
public static int Counter(node n) { int counter = 0; node head = n; while (head != null) { head = head.next; counter++; } return counter; }
@Eclipse-san
@Eclipse-san 3 жыл бұрын
Hey CS Dojo, I absolutely loved how you gave us a practice question. I felt really good after solving it ! My Solution in python: class Node: def __init__(self, data): self.data = data self.next = None def countNodes(self): while(self.next != None): print(self.data) class LinkedList: def __init__(self): self.Head = None def push(self, data): new_node = Node(data) new_node.next = self.Head self.Head = new_node def countNodes(self): temp = self.Head count = 0 while(temp): count += 1 temp = temp.next return count linked_list = LinkedList() linked_list.push(1) linked_list.push(2) linked_list.push(3) linked_list.push(4) print(f"The LinkedLists has {linked_list.countNodes()} Nodes.")
@Zerimarvin
@Zerimarvin 2 жыл бұрын
AaaAAAAaaaAAAAAAAAAaAAaaaaaAAAAAAAAAAAAAAAaaaaaAaAaAAAAAAaaaaaaaaaaaa
@Zerimarvin
@Zerimarvin 2 жыл бұрын
Aaa
@Zerimarvin
@Zerimarvin 2 жыл бұрын
Aaaa
@Zerimarvin
@Zerimarvin 2 жыл бұрын
Aaa
@Zerimarvin
@Zerimarvin 2 жыл бұрын
Aa
@stephaniemartinez1468
@stephaniemartinez1468 3 жыл бұрын
I used recursion to solve the problem. public static int countNodes(Main head){ if (head == null){ return 0; } else { return 1 + countNodes(head.next); } }
@debarkachakraborty3857
@debarkachakraborty3857 6 жыл бұрын
Thanks a lot man! You have explained it precisely for a beginner to understand. I would request you to post video for doubly and circular Linked list too.
@azimuth809
@azimuth809 5 жыл бұрын
*** C++ CODE *** // there are many ways to do that // You can make it by using Recursive way // if you want to append strings or another arguments you can do it ~ // You can add any function except mine like remove etc // ~ by using Templates // I would recommend you boos *** C++ Early Objects // Any questions, leave comment // *** GOOD LUCK *** #include using namespace std; class LinkedList // name of a class { protected: // our struct would be protected so we could manipulate data with Child Classes struct Node{ double data; // value in the node Node *next; // next pointer which points to the next node // Constructor Node (int data1, Node *next1 = NULL) { data = data1; next = next1; } }; Node * head = NULL; // pointing the head front of the node(Make it to point first node) public: void add(double); // adding function when we add the new value to our node int getSize(); // getting the size of a Node void DisplayList(); // Displaying the list }; // Adding function with argument double *** We can make it with template so we can ~ // ~ append any type of an argument void LinkedList::add(double number) // { Node *ptr = head; // both ptr and head points to the first node of the Node list if (head==NULL) head = new Node(number); // when it is empty just append the number else { while (ptr->next!=NULL) // Compile it if the first node not point to the NULL ***not next node { ptr = ptr->next; // go to the next node } ptr->next = new Node(number); // append the number instead of NULL } } // Displaying the LIST void LinkedList::DisplayList() { Node * ptr = head; // both of them begin from front Node list if(!head) // if it is empty return; while (ptr!=NULL) // while it is not empty { coutnext!=NULL) { len++; ptr= ptr->next; } return len+1; // since last node is NULL it would not add consider the last value ~ // ~ so we added it by ourselves } } int main() { class LinkedList list; list.add(1); list.add(2); list.add(3); list.add(5); list.add(12); // you can add your own code // code~~~ list.DisplayList(); cout
@tauseeqali3898
@tauseeqali3898 5 жыл бұрын
Thanks!
@zalavatari8416
@zalavatari8416 4 жыл бұрын
Nice
@zlove1010
@zlove1010 Жыл бұрын
thank you, going to analysis the code in an IDE appreciate it
@natestrings673
@natestrings673 Жыл бұрын
My solution is nowhere near optimized (most likely super elementary), but I'm proud it works - static int countNodes(Node head){ //assuming head != null int count = 1; Node temp = head.next; while(temp != null){ count++; temp = temp.next; } return count; }
@seanymiller2
@seanymiller2 3 жыл бұрын
This is the best explanation of a Linked List BY FAR. Great job!
@escrituratalks
@escrituratalks 3 жыл бұрын
Here is my solution def countNodes(head): If head.next == None : return 1 else: return 1 + countNodes(head.next)
@ogsconnect1312
@ogsconnect1312 5 жыл бұрын
public int getLength(ListNode head) { int i = 1; // counter while(head.next != null ){ i++; head = head.next; } return i; } // end method getLength
@dead-mb1zc
@dead-mb1zc 3 жыл бұрын
thank you thank you I finally REALLY understand how this shit works
@amrohany6818
@amrohany6818 5 жыл бұрын
swift 5.0 recursive function: func countNodes(_ node: Node) -> Int { // recursive function if node.next != nil { return countNodes(node.next!) + 1 } return 1 }
@rukna3775
@rukna3775 4 жыл бұрын
public class Main { public static void main(String[] args) { Node node1 = new Node(5); Node node2 = new Node(14); Node node3 = new Node(77); node1.next = node2; node2.next = node3; node3.next = null; LinkedList.printNodes(node3); } } public class Node { int data; Node next; Node(int data) { this.data = data; } } public class LinkedList { static int countNodes(Node node) { int i = 0; while(node != null) { ++i; node = node.next; } return i; } static void printNodes(Node node) { int nodes = countNodes(node); for(int i = 0; i < nodes; i++) { System.out.print(node.data + " "); node = node.next; } } }
@pranathikanamarlapudi2726
@pranathikanamarlapudi2726 5 жыл бұрын
hi sir, u explained it very well! just a small doubt- how does the doubly linked list prev node work? how will it know that prev is the previous one?
@arunakumari634
@arunakumari634 6 ай бұрын
From where I can find the advance link list concepts
@mythos257
@mythos257 5 жыл бұрын
class Node: def __init__(self, data, next=None): self.data = data self.next = next Head = Node(5,Node(1,Node(2,Node(8)))) def count_Nodes(head): count = 0 a = head while True: count += 1 if a.next == None: return count a = a.next print(count_Nodes(Head)) I used a different Generator because this way it's much more compact
@Tips4Tat
@Tips4Tat 5 жыл бұрын
Short and sweet
@yannick2247
@yannick2247 2 жыл бұрын
My solution java: int countNodes(Node head) { int counter = 1; boolean nextNodes = true; Node nextHead = head; while (nextNodes) { if (nextHead.next != null) { // next nodes inside counter++; nextHead = head.next; } else { nextNodes = false; } } return counter; }
@vanessashultz2330
@vanessashultz2330 4 жыл бұрын
I love your teaching! I learned a lot!
@ahmed_yussuf
@ahmed_yussuf 3 жыл бұрын
Thank you! I am taking Algorithm and data structure in community college. I think spending 900 dollars on that course the professor can not do half of what you do. BRAVO!
@isabellahernandez2403
@isabellahernandez2403 5 жыл бұрын
I really liked all of your visuals. They all really helped me. Especially having drawn out images next to the code. I really like how you explain everything as well.
@somyajain9526
@somyajain9526 3 жыл бұрын
int countNodes(Node head){ int count=0; while(head!=null){ count=count +1; head=head.next; } return count; }
@deanmurray7626
@deanmurray7626 3 жыл бұрын
or int countNodes (Node head) { if head == null return 0; return countNodes(head.next) + 1; }
@muratderekoylu4673
@muratderekoylu4673 6 жыл бұрын
My Java Code: int countNodes(Node head) { Node tmp = head; int counter = 0; while(tmp != null) { counter++; tmp = tmp.next; } return counter; }
@CBECH22
@CBECH22 5 жыл бұрын
I was looking at this and I confused myself. I was trying to challenge myself and was thinking this code might be one count short because you werent accounting for the first head. You would either need to start counter at 1 or increment counter by one at the end. Very well done though, and easy to read!
@SureshKumar-kd3fx
@SureshKumar-kd3fx 5 жыл бұрын
Counter=1 Not 0
@ikercasillas1786
@ikercasillas1786 5 жыл бұрын
@@SureshKumar-kd3fx it works when counter is set to 0 because it stills loops through and increments it.
@ikercasillas1786
@ikercasillas1786 5 жыл бұрын
@@SureshKumar-kd3fx in the video the loop was based on current.next and not current, that is the difference between his and Murat's code.
@SmartassEyebrows
@SmartassEyebrows 5 жыл бұрын
@@SureshKumar-kd3fx @Chance Bechly Actually, it is correct. Look closely at the order of the code; counter++ happens Before the jump to the next item. So starting at head, you increment the counter from 0 to 1 (thus counting the head), then you go to head.next, check if it is null, if not, increment counter from 1 to 2, and so on till you hit a null. If you started the counter at 1, in the case where there -is no list at all-, you would incorrectly count 1 node, when no nodes exist in the first place.
@thegaribovv
@thegaribovv 4 жыл бұрын
Thank you very much)), step by step and very simple.
@ryanlynch2674
@ryanlynch2674 6 жыл бұрын
Hey guys, I'm not sure if anyone has posted this before but if you wanted to solve this recursively you could use this: static int countNodes(Node head) { if(head.next == null) { return 1; } else { return countNodes(head.next) + 1; } }
@SplyGuy
@SplyGuy Жыл бұрын
I'm very late, but this is extremely helpful. Thank you.
@jushas9276
@jushas9276 4 жыл бұрын
Youuu are aaawesome👏👏👏👏...
@andreandrews6237
@andreandrews6237 6 жыл бұрын
my solution: int countNodes(Node head){ int result = 1; //should always start with one because if you have a head then 1 node by default, NOT 0 Node currentNode = head; while( currentNode.next != null){ result ++ (can also do += 1, style thing) try{currentNode = currentNode.next} catch (Exception e){break;} } return result; } try catch may not even be necessary, but can never be too careful lol, written in c# btw
@rintarouokabe7237
@rintarouokabe7237 2 жыл бұрын
assume that tail is the last box. tail = last box from the linkedlist Solution: int CountNodes = 1; //since we initially start at head and head also considered as nodes while(nodes!=tail+1){ if(nodes != null){ countNodes++; } return countNodes; }
@rintarouokabe7237
@rintarouokabe7237 2 жыл бұрын
btw guys im only a beginner in programming so pls don't judge my code but if there are some corrections or you've suggestion feel free to comment it thanks. :P
@AS-os3lj
@AS-os3lj 6 жыл бұрын
But why should we use a linked list?
@SudiptaKarmakar87
@SudiptaKarmakar87 6 жыл бұрын
Depends on use case. Like when you need fast (constant time) insert/delete in a list but you are not looking for dynamic access to any element of that list.
@nirash8018
@nirash8018 6 жыл бұрын
Its the same like an array, but with the advantage of being able to not having to insert the amount of objects you want to enter in the List. But tbh its just way too much work so i'd always go with the array
@SudiptaKarmakar87
@SudiptaKarmakar87 6 жыл бұрын
If you do not know any better the least you can do is not spread misinformation. It's NOT like an array. Instead a linked list is maintained using pointers to next node/element. And I'm not even sure what "being able to not having to insert the amount of objects you want to enter in the List" means.
@nirash8018
@nirash8018 6 жыл бұрын
saying that it’s LIKE an array doesn’t means it is an array dumbass. And if you don’t understand my sentences bcs in your poor country the education system is fucked I’m not to blame.. Please think before writing some shit
@SudiptaKarmakar87
@SudiptaKarmakar87 6 жыл бұрын
Appreciate your intellectual responses. Real class. "saying that it’s LIKE an array" is wrong by itself! And no, "being able to not having to insert the amount of objects you want to enter in the List" - does not make any sense in whichever language you try.
@joysehgal8105
@joysehgal8105 4 жыл бұрын
def countnodes(node): if node.next==None: return 1 else: return 1+countnodes(node.next)
@bruhop3074
@bruhop3074 3 жыл бұрын
I have been trying to learn LinkedList from yesterday, watched many tutorials, read many blogs but I was not getting the clarity as even the code of LinkedList is very intimidating. this video helped a lot!! I am finally a bit confident and ready to learn more about it and solve problems. Thank You Dojo!🙌
@ToyMachine22122
@ToyMachine22122 4 жыл бұрын
Like your videos! I get that linked lists are a required topic to understand for purposes of passing tests (either at university or for a job screening), but the reality is that linked lists are practically useless, at least in 99%+ of cases. Almost all of the time, you’d get much better performance using a dynamic array (called a vector in C++). I know: supposedly linked lists have better performance for random insertions and deletions. Supposedly. But the fact is that CPU caches work MUCH better with arrays than with linked lists. On average, Linked lists incur a cache miss EVERY TIME you want to advance your iterator, whereas dynamic arrays only incur a cache miss once per SizeOf(CPU Cache)/SizeOf(YourDataType) So yeah, nice explanation, but basically don’t use linked lists, *almost* ever. The only conceivable situation where linked lists win over vectors despite their poor cache performance is when you want to MAINTAIN AN ITERATOR TO A RANDOM POSITION in the list - a position where you KNOW that your next insertion or deletion will be performed. Such situation is very rare and I can’t even think of an example. So yeah, that’s linked lists, now don’t use them cause they almost always suck.
@raushankumarraman7259
@raushankumarraman7259 6 жыл бұрын
Sir please make more videos on python.
@Hateusernamearentu
@Hateusernamearentu 2 жыл бұрын
watched your video twice. This time finally get the "head" idea. Thank you !!! You simplify everything yet does not lose the key point!!!! Great Work!!!!
@JagroopSingh-wd6kj
@JagroopSingh-wd6kj 4 жыл бұрын
//Method returns count of Nodes int countNodes(Node head){ //This method returns the number of Nodes int count = 0; while(head != null){ head.next; count ++; } return count; }
@MandeepKaur-km3ds
@MandeepKaur-km3ds 4 жыл бұрын
Well explained !! one of the best resources for learning linkedList
@josedanielgallegos10
@josedanielgallegos10 4 жыл бұрын
Another solution using Python def countNodes_(self, headval): currentNode = headval.next_val if currentNode is not None: return 1 + self.countNodes_(headval.next_val) else: return 1
@briannnnn6743
@briannnnn6743 Жыл бұрын
Python code (not sure if it works): def Node_Counter(head): counter = 1 while(true): if head.next != None: counter+=1 head = head.next else: return counter
@Bestshivam
@Bestshivam 5 жыл бұрын
Really very helpful. Saw a lot of videos on LL but this code made concept very clear and the code was so simple. Thanks.plz complete this whole DS series...
@sooryajagadeesan7017
@sooryajagadeesan7017 4 жыл бұрын
int count ; while ( head ! = NULL) { count++; head= head-> next; } return count;
@mahaveerjanagouda77
@mahaveerjanagouda77 Ай бұрын
my code :(please do tell me if this has any case errors) public class Linked { int data; Linked link; Linked(int data,Linked link) { this.data = data; this.link = link; } static int countnum =0; public static int count(Linked link){ if(link!=null) { count(link.link); countnum++; return countnum; } else return countnum; } public static void main(String[] args) { Linked forth = new Linked(1, null); Linked third = new Linked(2, forth); Linked second = new Linked(3, third); Linked first = new Linked(6, second); count(first); System.out.println(countnum); } }
@asdfghjkl1770
@asdfghjkl1770 5 жыл бұрын
wow! good job ,yk! keep teaching us! you're amazing!
@fredianriko5648
@fredianriko5648 3 жыл бұрын
I hope you were my programming language teacher back in the college day, I didn't understand it until watching your explanation
@phucnguyenducanh
@phucnguyenducanh 6 жыл бұрын
Using pointer represent a NODE, another good way:)
@GunelMammadova93
@GunelMammadova93 6 жыл бұрын
Thank you very much for all these awesome videos with the best explanation I have seen so far!
@NoorAfshanFathima
@NoorAfshanFathima 5 жыл бұрын
JS: class Node{ constructor(data, next){ this.data = data this.next = next } } let head = new Node(4) let nodeB = new Node(5) let nodeC = new Node(6) let nodeD = new Node(7) head.next = nodeB nodeB.next = nodeC nodeC.next = nodeD console.log(head, nodeB, nodeC, nodeD) let countNodes = function(head){ let count = 0 if (head.data === undefined) return count if (head.next === undefined) return count++ let currentNode = head count++ while(currentNode.next !== undefined){ count++ currentNode = currentNode.next } return count } console.log(countNodes(head))
@gabrielmunoz2845
@gabrielmunoz2845 3 жыл бұрын
Best video I have seen in learning a concept. Thank you very much!
@md.shakibhassan8960
@md.shakibhassan8960 5 жыл бұрын
For PHP (please ,correct if I've made any mistakes) ------------------------
@wmrdwijerathna680
@wmrdwijerathna680 2 жыл бұрын
Thank you so much. your explanation was very clear and excellent. this was the first video that I learned about a linked list. your video helped me to understand linked Lists very well. Keep up the good work.
@EmadElSherif
@EmadElSherif 2 жыл бұрын
why assume the head is not null, meanwhile we can check it easily by starting counter from zero and checking the head first? like this: public static int numberofnodes(Node head) { int numberofnodes=0; Node currentnode= head; while(currentnode!=null) { numberofnodes+=1; currentnode=currentnode.next; } return numberofnodes; }
@egehanasal710
@egehanasal710 3 жыл бұрын
YES YES YES SO MUCH LOVE FOR YOU THANK YOU !!!
@mcoyid
@mcoyid 5 жыл бұрын
Middle?? This is confusing if the numers are even.
@thotamounika5633
@thotamounika5633 3 жыл бұрын
Wow Thank you so much for making the linked list easy to understand. :) You're awesome!
@sandhyas4802
@sandhyas4802 5 жыл бұрын
public static int countnode(Node head) { if(head.next!= null) { return 1+countnode(head.next); } else { return 1; } }
@richie.edwards
@richie.edwards 5 жыл бұрын
// Javascript function countNodes(headNode) { var next = headNode.next; if(next == null) { return 1; } else return 1 + countNodes(next); }
@chee_tash
@chee_tash 3 жыл бұрын
The syntax here might not be exact and not sure if this solution works 100% but I used recursion public int numberNodes(Node node){ int counter = 0; if(node.next != null){ counter++ return numberNodes(node.next) } return counter; } so basically if the node has a next node, we increment the counter and call the function again, if not we just return counter?
@eiramavepanambo543
@eiramavepanambo543 4 жыл бұрын
Thank you YK for your clear explanation and samples :)
@vigneshrajans5814
@vigneshrajans5814 4 жыл бұрын
Hi YK - Thanks for your valuable teaching.. I have a doubt While defining data type of next(attribute) - you gave datatype as class name.. How it works here..
@hariharasudhann17
@hariharasudhann17 5 жыл бұрын
def countNodes(head): total = 0 while hasattr(head, "next"): total += 1 head = head.next return total print(countNodes("d"))
@ove12lord73
@ove12lord73 4 ай бұрын
my solution: class LinkedList: def __init__(self,number=None,next=None): self.number=number self.next=next o1=LinkedList() o2=LinkedList() o3=LinkedList() o4=LinkedList() o1.number=1 o2.number=2 o3.number=3 o4.number=4 o1.next=o2 o2.next=o3 o3.next=o4 def number_object(objectt): size=0 while True: try: objectt=objectt.next size+=1 except: print(size) break number_object(o1)
@DelphyM
@DelphyM 7 ай бұрын
Have you realised, that using `current.next` in the `while()` loop as condition, will always consume the next node? See the footage at 14:46. I think, the way to do it is questioning if `current` is not `null`, like this: ``` private static List createListFromLinkedList(String linkedListName, ListNode current) { System.out.println("Linked List " + linkedListName); List list = new ArrayList(); while (current != null) { System.out.print(current.val); list.add(String.valueOf(current.val)); current = current.next; } System.out.println(" There are " + list.size() + " elements."); return list; } ```
@ilia9788
@ilia9788 4 жыл бұрын
javascript: var head = {num: 1}; var nodeA = {num: 2}; var nodeB = {num: 3}; var nodeC = {num: 4}; head.next = nodeA nodeA.next = nodeB; nodeB.next = nodeC; var count = 0; var currentNext = head.next; while(currentNext){ ++count; currentNext = currentNext.next } console.log(count)
Introduction to Recursion (Data Structures & Algorithms #6)
22:37
Learn Linked Lists in 13 minutes 🔗
13:24
Bro Code
Рет қаралды 306 М.
Spongebob ate Michael Jackson 😱 #meme #spongebob #gmod
00:14
Mr. LoLo
Рет қаралды 10 МЛН
Players vs Corner Flags 🤯
00:28
LE FOOT EN VIDÉO
Рет қаралды 75 МЛН
ML Was Hard Until I Learned These 5 Secrets!
13:11
Boris Meinardus
Рет қаралды 310 М.
Introduction to Trees (Data Structures & Algorithms #9)
10:30
Bjarne Stroustrup: C++ | Lex Fridman Podcast #48
1:47:13
Lex Fridman
Рет қаралды 1 МЛН
LinkedList vs ArrayList in Java Tutorial - Which Should You Use?
11:43
Coding with John
Рет қаралды 593 М.
Introduction to Linked Lists - Data Structures and Algorithms
21:20
How to Create a Linked List C++ Introduction to Linked Lists
12:24
Paul Programming
Рет қаралды 929 М.
Positional List Data Structure
4:23
David Sher
Рет қаралды 4,2 М.
Spongebob ate Michael Jackson 😱 #meme #spongebob #gmod
00:14
Mr. LoLo
Рет қаралды 10 МЛН