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

Поділитися
Вставка
  • Опубліковано 23 лис 2024

КОМЕНТАРІ • 1 тис.

  • @CSDojo
    @CSDojo  6 років тому +181

    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 UA-cam channel :)

    • @technicalilm8999
      @technicalilm8999 6 років тому +9

      make a video on hash tables and hashing please

    • @astonchui808
      @astonchui808 6 років тому +5

      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 років тому +1

      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 років тому +1

      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.

  • @ArmandoAlejandro2014
    @ArmandoAlejandro2014 5 років тому +153

    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.

  • @damiajayi2081
    @damiajayi2081 4 роки тому +46

    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;
    }
    }

  • @MesitaButClean
    @MesitaButClean Рік тому +6

    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++!!!

  • @zeno5053
    @zeno5053 4 роки тому +28

    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 роки тому +2

      a great solution but butting the "if" expression in the same line with the statement doesn't actually reduce a line.

    • @codekarlebhai
      @codekarlebhai Рік тому +1

      @@zydiz its not if, its ternary operator with combination of recursion(but yeh logic is same)

    • @balajiramadoss6014
      @balajiramadoss6014 2 місяці тому +1

      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

  • @Artouple
    @Artouple 3 роки тому +74

    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 2 місяці тому

      header.next.data will throw null pointer exception if header.next is null

  • @davidemilan59
    @davidemilan59 4 роки тому +787

    When a UA-cam video teaches you better than your programming professor at University lol

    • @TheJoaohc
      @TheJoaohc 4 роки тому +6

      Exactly!

    • @zclee7325
      @zclee7325 4 роки тому +10

      it always to be like that

    • @ahiduzzamanahir1338
      @ahiduzzamanahir1338 4 роки тому +21

      @Xiogenes You're paying money for the syllabus....lol

    • @ysheepy4907
      @ysheepy4907 4 роки тому +24

      Cant agree more. My professor explains it so terribly that my brain went spaghetti ...

    • @realnice3672
      @realnice3672 3 роки тому +2

      @@ysheepy4907 tasty lol

  • @ivanrsbr
    @ivanrsbr 6 років тому +28

    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.

  • @vivek3861
    @vivek3861 6 років тому +264

    Best and simplest teaching ever...thanks.

    • @waelassaf4740
      @waelassaf4740 5 років тому +8

      Bless Up.

    • @heavysaber9431
      @heavysaber9431 5 років тому +36

      I wish I learned programming at high school, all I did was play video games...

    • @aryanshmahato
      @aryanshmahato 5 років тому +4

      @@heavysaber9431 I feel lucky now

    • @heavysaber9431
      @heavysaber9431 4 роки тому +2

      @@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

  • @patrickmayer9218
    @patrickmayer9218 Рік тому +6

    *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.

  • @ericnarciso9156
    @ericnarciso9156 3 роки тому +2

    Python recursive count:
    def count_nodes(head, c=0):
    if head:
    c += 1
    return count_nodes(head.next, c)
    return c

  • @heidik1757
    @heidik1757 4 роки тому +21

    You're an incredible teacher. Hope these videos never end and stretch across even the most advanced of topics. Very enjoyable.

  • @ahmed_yussuf
    @ahmed_yussuf 3 роки тому +2

    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!

  • @tomseinfeld7124
    @tomseinfeld7124 5 років тому +23

    In JavaScript
    function countNode(node) {
    let totalNodes = 1;
    let myNode = node;
    while(myNode.next) {
    total++;
    myNode = myNode.next;
    }
    return totalNodes;
    }

    • @sourabhkumar3852
      @sourabhkumar3852 3 роки тому +7

      inside while loop it will be totalNodes++ . Rest everything is absolutely correct.

    • @The_Bruh_26
      @The_Bruh_26 2 місяці тому

      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

  • @Hateusernamearentu
    @Hateusernamearentu 2 роки тому +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!!!!

  • @kyrinky
    @kyrinky 6 років тому +9

    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.

  • @citec123x
    @citec123x 4 роки тому +7

    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*

  • @Eclipse-san
    @Eclipse-san 3 роки тому +15

    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.")

  • @zecool7041
    @zecool7041 4 роки тому

    recursive with python:
    def countNodes(node):
    if(not node.next):
    return 1
    else:
    return countNodes(node.next) + 1
    short way using ternary operator :
    def countNodes(node):
    return 1 if not node.next else countNodes(node.next) + 1

  • @randomorigami6416
    @randomorigami6416 3 роки тому +16

    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 Рік тому +1

      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.

  • @gangstaberry2496
    @gangstaberry2496 2 місяці тому

    I honestly love this series, even if I'm not doing Leetcode, it is so interesting and well-presented

  • @satan9487
    @satan9487 6 років тому +26

    I was struggling with this for ages! Thank you a lot

  • @MitraNami
    @MitraNami 3 роки тому +2

    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)

  • @acidtears
    @acidtears 4 роки тому +15

    You're the Khanacademy of programming! Love this series and your step-by-step explanations.

  • @LoopyELBARTO
    @LoopyELBARTO 3 роки тому

    this is my solution in python
    def countNodes(head):
    count = 1
    while head.next != None:
    count += 1
    head = head.next
    return count
    Thank you for the clear explanation!

  • @amrohany6818
    @amrohany6818 5 років тому +10

    swift 5.0 recursive function:
    func countNodes(_ node: Node) -> Int { // recursive function
    if node.next != nil {
    return countNodes(node.next!) + 1
    }
    return 1
    }

  • @johnmarkcabusog6560
    @johnmarkcabusog6560 3 роки тому

    In Javascript, this is my solution:
    const countnodes=(list)=>{
    let count= 1; // for the head
    let _tempHead = list.head;
    while(_tempHead.next !== null){
    count++;
    _tempHead = _tempHead.next
    }
    return count;
    }
    Nice Video! Thanks.

  • @seanymiller2
    @seanymiller2 4 роки тому +3

    This is the best explanation of a Linked List BY FAR. Great job!

  • @hariharasudhann17
    @hariharasudhann17 5 років тому +1

    def countNodes(head):
    total = 0
    while hasattr(head, "next"):
    total += 1
    head = head.next
    return total
    print(countNodes("d"))

  • @nimmiverma1565
    @nimmiverma1565 5 років тому +12

    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 5 років тому +1

      @@dungletien4676 if there is only 1 Node, temp.next will always be null, so while loop never executed,hence returned 1

  • @zaurs0
    @zaurs0 3 роки тому +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

  • @yiyingzhang9585
    @yiyingzhang9585 5 років тому +4

    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!

  • @SilverTheFlame
    @SilverTheFlame 2 роки тому

    Fantastic video.
    My Java attempt at the practice problem (haven’t seen the solution yet):
    public static int countNodes(Node head) {
    Node curr = head;
    int numNodes = 0;
    while (curr.data != null) {
    numNodes++;
    curr = curr.next;
    }
    return numNodes;
    }

  • @suyashsharma7088
    @suyashsharma7088 6 років тому +22

    You have the best explanation of all the UA-cam 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

  • @josedanielgallegos10
    @josedanielgallegos10 4 роки тому +2

    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

  • @ryanlynch2674
    @ryanlynch2674 6 років тому +14

    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 2 роки тому +1

      I'm very late, but this is extremely helpful. Thank you.

  • @dreysmith2076
    @dreysmith2076 Рік тому

    Helping people 5 years later. Thank you!

  • @highmaths7698
    @highmaths7698 6 років тому +18

    You're doing a great job CS. I have already recommended your channel to a dozen friends.
    Keep up the good work!

  • @jaimegarcia5157
    @jaimegarcia5157 5 років тому +2

    I'm taking an online course for school on data structures and it's very hard to learn complex topics without audio (yes my professor just posts reads and doesn't record herself explaining it). This really helped me out

  • @mythos257
    @mythos257 6 років тому +3

    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

  • @EswarKumar1
    @EswarKumar1 3 роки тому

    He definitely made it clear. I've been watching several videos to understand Linked list and this fella helped me understand it. Thanks

  • @aglovecraft
    @aglovecraft 5 років тому +112

    Did it recursively:
    int countNodes(Node head) {
    if (head.next == null) { return 1;}
    else {return 1 + countNodes(head.next);}

    • @leelakrishna5815
      @leelakrishna5815 5 років тому +12

      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 5 років тому

      .

    • @scoutiano4441
      @scoutiano4441 4 роки тому +1

      why would you do it recursively if you can do it using a while loop in a few lines?

  • @blebdapleb8771
    @blebdapleb8771 2 роки тому

    I'm new to formalized programming but have been programming for over 4 years (Java, C#, C++). I haven't checked other comments yet but here is my solution to that problem
    static int countNodes(Node head)
    {
    int nodes = 1;
    while(head.next != null)
    {
    nodes++;
    head = head.next;
    }
    return nodes;
    }

  • @emmettanderson9185
    @emmettanderson9185 6 років тому +23

    YK your amazing I love that you quit your high paying job at google to teach on UA-cam I hope your channel blows up and you become famous!

    • @UnrecycleRubdish
      @UnrecycleRubdish 4 роки тому +5

      looks like your wish became true. he has more than a million followers in 2020 =)

    • @realnice3672
      @realnice3672 3 роки тому +1

      @@UnrecycleRubdish yeah lol

  • @3faze
    @3faze Рік тому

    Thank you so much, 8th grader here learning, you just taught me the basics of linked lists

  • @isabellahernandez2403
    @isabellahernandez2403 5 років тому +37

    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.

  • @Nicolas-L-F
    @Nicolas-L-F 3 роки тому

    My solution for the method to count nodes in c++:
    static int CountNodes(Node head) {
    Node currentNode = head;
    for (int i = 1; i < i + 1; i++)
    {
    if (currentNode.Next != NULL) currentNode = *currentNode.Next;
    else return i;
    }
    }
    Edit: formating.

  • @ogsconnect1312
    @ogsconnect1312 6 років тому +10

    public int getLength(ListNode head) {
    int i = 1; // counter
    while(head.next != null ){
    i++;
    head = head.next;
    }
    return i;
    } // end method getLength

  • @gina7898
    @gina7898 2 роки тому

    Honestly this was a great gateway to linked lists

  • @muratderekoylu4673
    @muratderekoylu4673 6 років тому +64

    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 років тому +3

      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 років тому +3

      @@SureshKumar-kd3fx it works when counter is set to 0 because it stills loops through and increments it.

    • @ikercasillas1786
      @ikercasillas1786 5 років тому +1

      @@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 років тому +3

      @@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.

  • @jack-tu9gv
    @jack-tu9gv 17 днів тому

    Tq some much sir for this vedeo that u explain how linked list works and ceration of linked list i saw so many vedeos but i only found this vedeo only understandable for beginners

  • @debarkachakraborty3857
    @debarkachakraborty3857 6 років тому +4

    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.

  • @andreandrews6237
    @andreandrews6237 6 років тому +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

  • @narendrasabhani
    @narendrasabhani 4 роки тому +1

    Hello YK,
    This is my first self learned small program to find the numbers of nodes. Your teaching is really excellent.
    I have written it in C# as following,
    namespace ConsoleApp1
    {
    public class Node
    {
    int data;
    public Node next;
    public Node(int data)
    {
    this.data = data;
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Node head = new Node(4);
    Node nodeA = new Node(2);
    Node nodeB = new Node(3);
    Node nodeC = new Node(10);
    Node nodeD = new Node(2);
    Node nodeE = new Node(23);
    Node nodeF = new Node(123);
    head.next = nodeA;
    nodeA.next = nodeB;
    nodeB.next = nodeC;
    nodeC.next = nodeD;
    nodeD.next = nodeE;
    nodeE.next = nodeF;
    System.Console.WriteLine($"Total numbers of nodes are : {CountNodes(head)}");
    }
    static int CountNodes(Node head)
    {
    int totalCount = 1; // consider count of head as 1
    Node currentNode = head;
    while (currentNode.next != null)
    {
    totalCount++;
    currentNode = currentNode.next;
    }
    return totalCount;
    }
    }
    }

  • @varmarocks009
    @varmarocks009 5 років тому +35

    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)

  • @natestrings673
    @natestrings673 Рік тому +1

    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;
    }

  • @hamiltonkahonde7939
    @hamiltonkahonde7939 5 років тому +28

    I love this dude!!! He explains this sooo damn well

  • @syr3472
    @syr3472 6 років тому

    the best thing about these videos are how simple they are to understand... by far the best tutorials on youtube

  • @technicalilm8999
    @technicalilm8999 6 років тому +12

    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))

  • @alansaldivares
    @alansaldivares 4 роки тому

    This is by far one of the best explanations I've ever seen about Linked Lists, especially for people like me that don't have a CS background.

  • @himanshuupreti9457
    @himanshuupreti9457 4 роки тому +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..

  • @iamvan7243
    @iamvan7243 Рік тому

    This was my code for the question, pretty self-explanatory if you trace it:
    static int count(Node head){
    int counter=1;

    while(head.next!=null) {
    //starting every loop the "head" within the while parameter will be replaced with "head.next", therefore the second iteration would be //head.next.next => head.next.next.next => head.next.next.next.... Stacking and adding more next attributes that until the next iteration value // finally results in a "null."
    head=head.next;
    counter++;

    }
    return counter;
    }

  • @vanessashultz2330
    @vanessashultz2330 4 роки тому +3

    I love your teaching! I learned a lot!

  • @chiho8119
    @chiho8119 3 роки тому

    Best simple explanation about linked list thusfar on UA-cam.

  • @piccolo111
    @piccolo111 5 років тому +41

    *** 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

  • @ardamoin3859
    @ardamoin3859 2 роки тому

    my solution as a beginner in python:
    def countNodes(head):
    node_counter = 1
    while head.next != None:
    node_counter += 1
    head = head.next
    return node_counter

  • @HungNguyen-oz1jc
    @HungNguyen-oz1jc 6 років тому +16

    Can you please next one do using LinkedList for Stack and Queue?

  • @goldener-reiter
    @goldener-reiter Рік тому

    Nice, excellent, brilliant, amazing video. Here's my solution, implemented in Java:
    public class Main {
    public static void main(String[] args) {
    Node head = new Node(6);
    Node nodeB = new Node(3);
    Node nodeC = new Node(4);
    Node nodeD = new Node(2);
    head.next = nodeB;
    nodeB.next = nodeC;
    nodeC.next = nodeD;
    System.out.println("The number of nodes are " + countNodes(head));
    }
    static int countNodes(Node head){
    int count = 0;
    Node auxNode = head;
    while(auxNode.next != null){
    count++;
    auxNode = auxNode.next;
    }
    return count;
    }
    }
    The static method receives a Type Node object, saves it into an auxiliar Object, while the next Object referred by the Link List is not null, it keeps adding 1 to the count and jumping into the next Node.
    I hope it helps. Cheers!

  • @pranathikanamarlapudi2726
    @pranathikanamarlapudi2726 5 років тому +3

    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?

  • @deionejack6115
    @deionejack6115 2 роки тому

    Really man ur explaination was much better than all the site lecture I have gone through

  • @JagroopSingh-wd6kj
    @JagroopSingh-wd6kj 5 років тому +3

    //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;
    }

  • @CuccoCodes
    @CuccoCodes 2 роки тому

    THANK YOU BRO! I LOVE LEARNING FROM PEOPLE WHO ARE SMARTER THAN ME!

  • @raushankumarraman7259
    @raushankumarraman7259 6 років тому +8

    Sir please make more videos on python.

  • @sukumarbabudhanasekar6762
    @sukumarbabudhanasekar6762 5 років тому

    You are a Good Teacher!!
    // C#
    public static int CountNodes(Node head) {
    if (head == null) return 0;
    bool isNextAvailable = true;
    int count = 1;
    Node container = head;
    while (isNextAvailable)
    {
    if (container != null)
    {
    count++;
    container = container.next;
    isNextAvailable = true;
    }
    else isNextAvailable = false;
    }
    return count;
    }

  • @TorIvanBoine
    @TorIvanBoine 6 років тому +8

    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 років тому +1

      dynamic allocation in memory, i guess. items of same collection can be stored in different locations of memory...

    • @delaghetto0
      @delaghetto0 5 років тому

      ua-cam.com/video/_jQhALI4ujg/v-deo.html

    • @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.

  • @LaurenceWilson-cy9xe
    @LaurenceWilson-cy9xe 26 днів тому

    Been searching for a video that goes through the info like this while building the class. Spot on!

  • @codingwithsam9194
    @codingwithsam9194 6 років тому +163

    hey sir. a 12 year old boy is inspired by you

    • @mryup6100
      @mryup6100 4 роки тому +6

      Keep it up!

    • @scum3112
      @scum3112 4 роки тому +10

      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 роки тому +7

      im 13 :D

    • @pratapkumarsahu8717
      @pratapkumarsahu8717 4 роки тому +1

      Me too

    • @Nicolas-L-F
      @Nicolas-L-F 3 роки тому +1

      16 here, keep it up man

  • @fredianriko5648
    @fredianriko5648 3 роки тому +2

    I hope you were my programming language teacher back in the college day, I didn't understand it until watching your explanation

  • @tailcatch5704
    @tailcatch5704 4 роки тому +12

    I learned in 20 minutes what my teachers were trying to teach me for 2 hours...

    • @suman-majhi
      @suman-majhi 3 роки тому +4

      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

  • @weixu7675
    @weixu7675 5 років тому +1

    *Python code:*
    def countNodes(head):
    i = 0
    point = head.next
    while point:
    i += 1
    point = point.next
    return i+1

  • @AS-os3lj
    @AS-os3lj 6 років тому +6

    But why should we use a linked list?

    • @SudiptaKarmakar87
      @SudiptaKarmakar87 6 років тому +4

      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 років тому +3

      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 років тому +10

      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 років тому +1

      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 років тому +3

      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.

  • @arthurandrade1763
    @arthurandrade1763 9 місяців тому

    def countNodes(head):
    if head.next == NULL:
    return 1
    # n represents nodes after current node
    n = countNodes(head.next)
    return n + 1

  • @gabrielmunoz2845
    @gabrielmunoz2845 3 роки тому +1

    Best video I have seen in learning a concept. Thank you very much!

  • @wmrdwijerathna680
    @wmrdwijerathna680 2 роки тому +1

    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.

  • @nikhilspatne
    @nikhilspatne 3 роки тому

    Python Code:
    def countNodes(self):
    count = 0
    itr = self.head
    while itr:
    count +=1
    itr = itr.next
    print(count)
    return

  • @broswhoknowstuff
    @broswhoknowstuff 3 роки тому

    My topic today Linked-lists and Bubble Sort. Here's my Python work for the evening. Excellent teacher! I'm 64 and self-taught. So, if I can learn to code - everyone can. Just code it. :)
    class Node:
    def __init__(self, data=None):
    self.data = data
    self.next = None
    class Linked:
    def __init__(self):
    self.head = None # has attribute 'head' assigned to None
    def show(self):
    node = self.head
    while node is not None:
    print(node.data)
    node = node.next
    def add(self, new ):
    new_node = Node(new) # create an instance of Node
    new_node.next = self.head # points to the 2nd element
    self.head = new_node
    def count_nodes(self):
    count =1
    current_head = self.head
    while current_head.next != None:
    current_head = current_head.next
    count += 1
    return count
    # create an instance of class Link
    link2 = Linked()
    # create a new Node()
    my_node = Node(6)
    # add to linked list
    link2.head = my_node
    link2.add(3)
    link2.add(5)
    link2.add(2)
    link2.show()
    print(f"The node count: {link2.count_nodes()}")

  • @virjeeva
    @virjeeva 3 роки тому

    Simplifying teaching of complex topic in Java , . The way explaining things what is happening inside the linked list side by side code details are simply great . One of the best teaching oh the topic. Thanks friend.

  • @harshvardhantiwary402
    @harshvardhantiwary402 2 роки тому

    In Python
    def countNodes(self):
    count = 0
    start = self.head
    while start:
    count += 1
    start = start.next
    print("Number of Nodes : " +str(count))

  • @kuroodo_
    @kuroodo_ 4 роки тому

    My solution in Java. Any advise/productive criticism appreciated.
    public static int countNodes(Node head) {
    Node current = head;
    int count = 0;
    while (current != null) {
    count++;
    current = current.next;
    }
    return count;
    }

  • @joysehgal8105
    @joysehgal8105 4 роки тому +1

    def countnodes(node):
    if node.next==None:
    return 1
    else:
    return 1+countnodes(node.next)

  • @gardensville101
    @gardensville101 8 місяців тому

    You have a great talent as a teacher. You should consider making that your profession because you rock!

  • @AshishKumar-cy7dx
    @AshishKumar-cy7dx 2 роки тому

    This is the best video on data structure. Thanks a lot for beautiful explanation.

  • @purrees
    @purrees 6 років тому

    public void countNodes(Link head) {
    int count = 0; //Initialize counter to 0
    if(head != null) { //If first link isn't empty, add 1 to the counter
    count = 1;
    }
    while(head.next != null) { //As long as each link after the head isn't null, increment counter by 1
    count++;
    head = head.next;
    }
    System.out.println("Count: " + count); //Print out total count
    }

  • @escrituratalks
    @escrituratalks 3 роки тому +1

    Here is my solution
    def countNodes(head):
    If head.next == None :
    return 1
    else:
    return 1 + countNodes(head.next)

  • @YellowHalo
    @YellowHalo 2 роки тому

    My solution is in Java: public int countNodes(Node head){
    Int count=0; //counter variable
    While(head!=null){ count++;
    head=head.next;} //assigns next node reference to head
    return count;

  • @haribattula5187
    @haribattula5187 2 роки тому

    using recursion in python we can find no of nodes like this:
    def countNodes(head):
    if head.Next!=None:
    return 1+countNodes(head.Next)
    else:
    return 1
    print(countNodes(Head))

  • @paul__wainaina
    @paul__wainaina Рік тому

    func (ll *LinkedList)CountNodes()int{
    var count=0
    var x=ll.Head
    for{
    if x==nil{
    break
    }
    count++
    x=x.nextNode
    }
    return count
    }

  • @zaymaungmaungmyint8142
    @zaymaungmaungmyint8142 5 років тому

    your solution is simple and perfect.
    I wanna add one condition =>
    if(head == null) {
    return 0;
    }

  • @benalves1656
    @benalves1656 5 років тому +1

    def countNodes(box):
    count = 1
    while box.next:
    count = count + 1
    box = box.next
    return count

  • @kotasdanroda5132
    @kotasdanroda5132 4 роки тому

    I literally understand this compared to my modules I suffered a lot because this wacky visuals in my module. Thanks sir, this help a lot this time of crisis.