Linked List in C/C++ - Insert a node at nth position

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

КОМЕНТАРІ • 360

  • @MrPortraitsofpast
    @MrPortraitsofpast 9 років тому +19

    this guy is so badass. Thorough, precise, not watered down, and still entertaining...dope.

  • @manavaswani2423
    @manavaswani2423 4 роки тому +65

    Mr. Animesh Nayan! You're gem of an instructor man, seriously. ❤️

    • @yashaswani8813
      @yashaswani8813 3 роки тому +11

      good to see another Aswani learning to code haha

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

      brother these content was not by animesh nayan but by lord harsha suryanaryaana known as humble fool

  • @aaqif91
    @aaqif91 11 років тому +23

    Wouldn't have been able to perform as well as I am on my C programming course without your videos! You are awesome! Thank you for taking the time to do this.

  • @PHYSICSGURUSANTOSHYADAV
    @PHYSICSGURUSANTOSHYADAV 10 років тому +43

    Best lecture on internet about programming methodology...i havent seen ever such a clear explanation about each topics..really you all are doing such a great jobs..thank u so much sir....

  • @AZihad10
    @AZihad10 4 роки тому +9

    I don't usually go around praising yt tutorial makers but this visualization process is very cool. You have an unique way of teaching. Thanks and Good luck man

  • @arunraj11s
    @arunraj11s 6 років тому +139

    for (i=1;inext;
    }
    this would have avoided unnecessary confusions for beginner.

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

      thx

    • @efstacrazydaisy
      @efstacrazydaisy 5 років тому +15

      I must say im not confused at all and not a beginner... by watching this video i feel like an expert! Congrats to the team behind it..love you India

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

      your comment helped a lot

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

      Actually you would get a segmentation fault (core dumped) due to not properly allocating memory.

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

      if i want to insert my node at second position. Then n=2, the loop wont work for this since n-1=1 here. Please help

  • @davidhasovic
    @davidhasovic 7 років тому +59

    // Code in C with slightly clearer variable names in the main part of the program
    // To compile with gcc run this: "gcc -o linked_list2 linked_list2.c ; ./linked_list2" assuming that your file name is named: "linked_list2.c"
    #include
    #include
    struct Node {
    int data;
    struct Node* next;
    };
    struct Node* head;
    void Print () {
    struct Node* temp = head;
    while (temp != NULL){
    printf ("%d", temp->data);
    temp = temp->next;
    }
    printf("
    ");
    }
    // The meat of the program
    void Insert (int data, int position) {
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->data = data;
    newNode->next = NULL;
    if (position == 1) {
    newNode->next = head;
    head = newNode;
    return;
    }
    struct Node* previousNode = head;
    for (int i = 0; i < position - 2; i++) {
    previousNode = previousNode->next;
    }
    newNode->next = previousNode->next;
    previousNode->next = newNode;
    }
    int main () {
    head = NULL;
    Insert (2, 1);
    Insert (3, 2);
    Insert (4, 1);
    Insert (5, 2);
    Print ();
    }

    • @RownitaTasneem-qf5sr
      @RownitaTasneem-qf5sr 5 років тому +1

      Thanks a million for your code.

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

      @@shyamsundarjha5913 Because We have Started taking Node 1 as position 1 not Position 0 and we have started for loop from i=0 and at When i will be at Position-2 Our temp2 will be at position-1 Which we need.If You will take i=1 then it will be upto pos-1.

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

      @@shyamsundarjha5913 because you always start on the head node and not before it. So if we do n-2 then we are eliminating a iteration to arrive at the n-1 node

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

      you did not typecast the malloc part buddy

  • @johnnychan6755
    @johnnychan6755 9 років тому +16

    The simulation is excellent! It definitely has helped me visualize the algorithm better. Thank you!

  • @georgemacintyre3333
    @georgemacintyre3333 8 років тому +2

    I just want to say thank you so much. These videos are amazing. I understand linked lists so well thanks to these, and I've never seen a programming concept explained so well, not even from my teachers. You are the best!

  • @ChildofDestiny22
    @ChildofDestiny22 7 років тому +2

    Big thanks from Indonesia, this is no doubt one of the best programming tutorial in youtube, you explained things clearly! You deserve more subscribers!

  • @yichizhang795
    @yichizhang795 9 років тому +12

    It is arguably one of the best quality programming video I have ever seen. Thank you so much for making this video. It really helped me out from link list! God bless you sir :)

  • @3216mohit
    @3216mohit 9 років тому +104

    one of the best tutorial on list list... good work!!!!! first time i understand whats this shit is

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

    salute lord harsha suryanaryana you will always remembered

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

    You have explained things very well. I had to watch it 4 to 5 times but it really worth it. Thank you so much.....!

  • @sramaiah110784
    @sramaiah110784 7 років тому +12

    You guys are amazing. Very detailed and clear in explaining. Keep up the good work.

  • @TheVictorEffect
    @TheVictorEffect 5 років тому +32

    I'm studying for my finals right now and I'm just now learning my professor literally copied most of your videos to teach us C. Like the code in his slides are IDENTICAL from this tutorial. So funny yet sad I'm paying thousands of dollars when its free here

    • @Warrior_x_vigilante100
      @Warrior_x_vigilante100 6 днів тому

      Hence proved:- The indian education system is a fucking scams, and the institutions are scammers.

  • @rahuldevlenka505
    @rahuldevlenka505 5 років тому +40

    here's the source code for c:
    #include
    #include
    void Insert(int, int);
    void print();
    struct Node
    {
    int data;
    struct Node* next;
    };
    struct Node* head;
    void main()
    {
    head=NULL;
    Insert(3,1);
    Insert(2,2);
    Insert(4,2);
    print();
    }
    void Insert(int data, int n)
    {
    struct Node* temp1=(struct Node*)malloc(sizeof(struct Node*));
    int i;
    temp1->data=data;
    temp1->next=NULL;
    if(n==1)//empty list
    {
    temp1->next=head;
    head=temp1;
    return;
    }
    struct Node* temp2=head;
    for(i=0;inext;//to point temp2 to (n-1)th node after loop
    }
    temp1->next=temp2->next;// point new (nth)node to next node
    temp2->next=temp1;// to point the previous( n-1 th) node to new node
    }
    void print()
    {
    struct Node* temp=head;
    while(temp!=NULL)
    {
    printf("%d\t",temp->data);
    temp=temp->next;
    }
    puts("");
    }

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

      The same logic in c++ is not working

    • @МаоЦзэдун-б5с
      @МаоЦзэдун-б5с 5 років тому

      I have a question. About changing 1st item second time! Clearly that code is wrong, if i want to insert something at first position, this code will point my new node to head "temp1=>Next = head" and then assign head to my new node "head = temp1", which means that "head=>Next == head"(head points to itself), and if we had a data in our list then we would lose it and also have a unnecessary occupied space in our memory, cause C/C++ do not have something like garbage collector.
      Why do this pal? Something like "//empty list" means nothing in logic, you make your program work properly and you do not make comments asking to not do that second time,while in your example you do that for second time and show that code is working just fine.
      (i mean in this comment he didn't made that mistake but video author did)

    • @МаоЦзэдун-б5с
      @МаоЦзэдун-б5с 5 років тому

      ​@@ankanmaiti9864​ do you face the same problem as i described? ^

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

    Thank you for the video.
    We should also take care of invalid position scenario...
    Eg.if list has just 3 nodes and user does insert( data=1 , n= 65 ),
    Inside for(i=0;inext; } will crash..
    correct way is for(i=0;inext!=NULL ;i++) and node can be inserted at end.
    Similarly for empty list and invalid position , code can be changed to
    if (pos == 1 || (head == NULL && pos != 1) )
    {
    newNode->next = head;
    head = newNode;
    return;
    }

  • @mycodeschool
    @mycodeschool  11 років тому +3

    Well, in that case - you will not have to traverse the list from head. You will only adjust some links in constant time.

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

    for those who are confused about "n-2", just start your loop with i=1 (which means head n=1) then you can run your loop until "n-1" to avoid confusion.

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

      Thank you!! 🙏🙏🙏🙌

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

      @@bhaswardutta8493 if we wanna insert in 2 position n=2,so i

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

      @@convolutionalnn2582 IN THAT CASE the loop will not run because we require temp2 to be at head position which it already is

  • @mycodeschool
    @mycodeschool  11 років тому +7

    Thanks Prashant :)

  • @priyankaradhakrishnan894
    @priyankaradhakrishnan894 9 років тому

    thank you sir.initially felt data structures very difficult but gained more confidence after watching these videos.

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

    you are like a god for me I have never seen this type explanation very nice

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

    if your program is going to infinity loop or not working.
    Just make these Changes in the for loop in the insert function :
    for (int i = 1; i < n - 1; i++)
    {
    temp2=temp2->next;
    }

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

    it's very helpful and amazing for me,thank you so much,GOOD LUCK

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

    one of the best explained

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

    I'm very grateful for all these videos and I think it's hilarious that you put subtitles, even tho honestly I think it's better they are there. cheers :)

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

    Great explanation. Just one thing about process layout - It is ".code -> .data/.bss -> heap -> stack" rather than ".code -> .data/.bss -> stack -> heap" :)

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

    I got an exam in a weeks time but the way this guy is explaining,it has given me confidence that i can take the exam today,,,,,thumps high & fuck haters

  • @Naveen-ef2dg
    @Naveen-ef2dg 6 років тому

    Best possible way to learn datastructure is through this playlist...
    Well done sir

  • @AmanKumar-nj5sz
    @AmanKumar-nj5sz 3 роки тому +1

    Literally the best

  • @vijaykumarkari
    @vijaykumarkari 4 роки тому +4

    wow! really amazing i learned inserting a node in linked list.thank you:)

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

    THAT👉 temp2 = head 👈IS MY SAVIOR, THE REASON WHY IT ALWAYS "SEGMENTATION FAULT" great thanks to you man 👍

  • @mingx009
    @mingx009 10 років тому +1

    Very very clear lecturing. Thanks a lot.

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

    THank you for making this gem videos , i will definitely reach to my destination by watching this playlist.

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

    Your videos are so clear ...thanks !! Which is that software u r using to run the code ? Can u link it or tel abt it ?

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

    will this code work if try to insert at 3 rd position
    cause u have only done insertions at first and last node

  • @arkapravadutta8319
    @arkapravadutta8319 6 років тому +2

    First of all , amazing explanation.
    Doubt:
    1. Why use the if statement at all when n=1, why not just use a while loop and do n--;
    2. I am aware that it has something to do with not giving a position that does not exist in the list but i am still not clear as to why we are giving only 1 and 2 as the positions where we want to enter the numbers

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

    WHO IS THE GUY BEHIND THIS AMAZING CHANNEL ?? (voice seems to be from) Indian English accent )
    thanks a lot brother for making this channel and for explaining each and every possible query in detail

  • @01aniruddhaislam26
    @01aniruddhaislam26 2 роки тому

    Very good tutorial. I wish he continued teaching like this.

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

    at 12:17 what if we write delete temp at the end of insert function, when I coded it with writing delete temp it worked perfectly but my question is that when the control goes back it automatically deletes the temp pointer as I am doing manually in my code, so when its deleted it should also delete the data and next pointer assocaited with temp in heap but its not deleted here when the control goes back, Please tell why??

  • @aasimbaig01
    @aasimbaig01 7 років тому

    this is easy to understand and explain :)
    void insert(int pos,int val) {
    //declaration
    Node *temp1=head;
    Node *temp=new Node;
    //inserting value
    temp->data=val;
    temp->next=NULL;
    if(pos==1){
    temp->next=head;
    head=temp;
    return;
    }
    else{
    for (int i=2;inext;
    }
    temp->next=temp1->next;
    temp1->next=temp;
    }

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

    Should i share my code about linklist in C++. So i like the way you explain the things and i want to learn more from you.

  • @mustafagamal8818
    @mustafagamal8818 8 років тому +2

    First Thank you so much for this great explaining , second I'd like to ask some question please, why this program can't deal when n > 2 ? I've tried to deal with third or force place or any place greater than 2 it doesn't work still put the data in the second place ??

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

      It will work Just add
      temp1->next=NULL;
      in the last line of insertNode.For Some Reason this Program Was Going in Infinite Loop but it is okay with this addition.

  • @girishchandrakuniyal
    @girishchandrakuniyal 9 років тому +1

    which compiler are used in above videos?? it looks pretty good than turbo c..

  • @01aniruddhaislam26
    @01aniruddhaislam26 2 роки тому

    I think the heap illustration in 14:53 is incorrect . 150 is written under head but it shown to point to 50.

  • @pankajgupta6293
    @pankajgupta6293 6 років тому +1

    Working code in C++ :
    #include
    using namespace std;
    struct node
    {
    int data;
    node* next;
    };
    node* head;
    void Insert(int data,int n)
    {
    node* temp=new node();
    temp->data=data;
    temp->next=NULL;
    if(n==1)
    {
    temp->next=head;
    head=temp;
    }
    else
    {
    node* temp1=head;
    for(int i=0;inext;
    }
    temp->next=temp1->next;
    temp1->next=temp;
    }
    }
    void Print()
    { cout

  • @SahilAnsari-ix6mu
    @SahilAnsari-ix6mu 8 років тому +1

    Sir can i ask a personal question from where u have studied computer because your lectures are too good i want to download each and every lectures but it is taking much time so i m downloading one by one it is helping me a lot I am a first year btech Computer science student...

    • @himanshu6489
      @himanshu6489 8 років тому +1

      he has done his engineering from Netaji Subhash Institute of Technology, New Delhi.

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

      @@himanshu6489 no. He has studied from IIIT, Allahabad.

  • @abdulkayuem3247
    @abdulkayuem3247 7 років тому

    Best lecture i have ever seen

  • @hailongzhao2887
    @hailongzhao2887 8 років тому

    Posting an implementation which uses the while loop as well as checks boundary conditions:
    /*
    Insert Node at a given position in a linked list
    head can be NULL
    First element in the linked list is at position 0
    Node is defined as
    struct Node
    {
    int data;
    struct Node *next;
    }
    */
    Node* InsertNth(Node *head, int data, int position)
    {
    Node *node = new Node;
    node->data = data;
    node->next = NULL;
    Node *prev = NULL;
    Node *current = head;
    int n = 0;
    while (n < position && current != NULL) {
    prev = current;
    current = current->next;
    n++;
    }
    if (prev == NULL) {
    node->next = head;
    return node;
    }
    prev->next = node;
    node->next = current;
    return head;
    }

  • @vukstefanovic6275
    @vukstefanovic6275 7 років тому +1

    your videos are great !!!!! its a shame u don;t make them any more :(

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

    Great series. I love your page. In the end however the value of head should be the address of 4 (which is 50 not 150) since head has changed.

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

    awesome, what tool you are using for whiteboarding?

  • @paulwatkin6360
    @paulwatkin6360 10 років тому +1

    My favouite quote in this video is "Head will not be accessible everywhere!", such is life lol! Great work though, really good video.

  • @suyashschmidt6985
    @suyashschmidt6985 9 років тому

    Explanation is great. Could you tell how are you writing this code? I mean what compiler? Xcode ?

  • @OscarElnecave
    @OscarElnecave 7 років тому +1

    What about using a typedef to declare the structure? thanks

  • @ADNANAHMED-eo5xx
    @ADNANAHMED-eo5xx 4 роки тому

    wow this was confusing, but it was fun, because when u understand after confusion, it is understood better, thanxxxxxxxxxx

  • @shubhamgoswami8751
    @shubhamgoswami8751 7 років тому

    no any teachers explains in such a simple way...

  • @usama57926
    @usama57926 6 років тому +1

    thanks for such an amazing playlist

  • @mokodsmartkwangkhoontod2250
    @mokodsmartkwangkhoontod2250 7 років тому

    8:40 Why *temp2 isn't declared by new Node () function ?
    Reply me please. Thank you.

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

      see the complete video ,it is explained in the end

  • @ayushyadav4076
    @ayushyadav4076 9 років тому

    we will write struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node*)) or
    struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node))

    • @MaiPham-js2hq
      @MaiPham-js2hq 6 років тому

      thanks for your help. I finally find out why the code doesn't run. phewww!!!

  • @AnkushPareOfficial
    @AnkushPareOfficial 9 років тому

    Sir,if we ask user to enter position for data and initially user enter position greater than 1 lets say 10. so how can we handle this situation???

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

    Great tutorial👍.
    Doubt: why didn't you deallocate memory..from heap..???

  • @kandy1249
    @kandy1249 7 років тому +2

    before IF condition in insert function ... do we really need that " temp1->next =null "? because it's just an extra step we don't need to perform I think.

    • @mrbilalkhan
      @mrbilalkhan 7 років тому +1

      If condition checks if the new entry is in the first position of the linked list. whereas temp1->next =null is placed outside the if block if in case the list is empty.

    • @AtulSharma-hy9yo
      @AtulSharma-hy9yo 6 років тому

      yes we do need it in case if list is empty!

  • @mashable8759
    @mashable8759 8 років тому

    BEST LECTURE EVER

  • @ahmedsafwat1460
    @ahmedsafwat1460 8 років тому +1

    Thanks for the great explanation !
    but the code doesn't work although it compiles...have you tried it yourself?

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

    This video made my day..really awesome video to understand

  • @amaytrivedi
    @amaytrivedi 8 років тому +1

    Liked your video but can u tell me if we assign address of head node to the node we want in d place of head why are we doin temp->next=head and not simply temp=head;..Thankyou:)

  • @sandhyathugutla4228
    @sandhyathugutla4228 7 років тому +1

    how does for loop works in insertion???please explain

  • @GagandeepSingh-tl7zg
    @GagandeepSingh-tl7zg 4 роки тому

    Java code continues.
    For this I believe we need to make changes to the add function. We need to introduce a new variable size.
    We have added size++ to the add function and to the insertAtFront function.
    Complete code:
    package algorithmswithjava;
    /**
    * Linked list implementation in Java.
    *
    * @author Gagandeep Singh
    */
    public class LinkedList {
    private final Node head;
    private int size = 0;
    public LinkedList() {
    head = new Node();
    }
    // We can perform following operation on the linked list.
    // 1. Insert a data.
    public void add(int data) {
    Node address = head;
    while (address.next != null) {
    address = address.next;
    }
    Node newNode = new Node();
    address.next = newNode;
    newNode.data = data;
    size++;
    }
    // 2. Traversal
    public void print() {
    Node address = head;
    if (address.next == null) {
    System.out.println("Empty");
    return;
    }
    while (address.next != null) {
    System.out.println(address.next.data);
    address = address.next;
    }
    }
    public void insertInFront(int data) {
    Node pointer = head;
    if (pointer.next == null)
    add(data);
    else {
    Node node = new Node();
    node.next = pointer.next;
    pointer.next = node;
    node.data = data;
    size++;
    }
    }
    public void insertAt(int data, int position) {
    Node pointer = head;
    // Check that no invalid field is sent.
    if (position > size && position < 0) {
    throw new RuntimeException("Invalid index location. Choose from range 0 - " + size);
    }
    // Checks if we have to insert at the end.
    else if (position == size) {
    add(data);
    }
    // Since we already have the function in place for inserting at the beginning.
    else if (position == 0) {
    insertInFront(data);
    } else {
    for (int i = 0; i < position; i++) pointer = pointer.next;
    Node node = new Node();
    node.next = pointer.next;
    pointer.next = node;
    node.data = data;
    size++;
    }
    }
    public int getSize() {
    return size;
    }
    /**
    * Private static inner class to create a node for the linked list.
    */
    private static class Node {
    private int data;
    private Node next;
    }
    }

  • @krishnadogney7396
    @krishnadogney7396 8 років тому +2

    I am using codeblock compiler to run this program and there is zero warning and zero error but if I try to run the program I get a message saying that the data structure has stopped working. Please help.

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

      Krishna Dogney do you get solution of this problem i am suffering frm same one

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

      Add #include
      May be it can help.
      Because of malloc

  • @jitu_jackjp9552
    @jitu_jackjp9552 7 років тому

    wonderful ......this is some special type of lacture......

  • @manishjoshi539
    @manishjoshi539 9 років тому +11

    why not (n-1) instead of (n-2) there ?
    struct Node* temp2 = (struct Node*)malloc(sizeof(struct Node*));
    for(i=0;inext;
    }

    • @jaspreetpawa
      @jaspreetpawa 7 років тому +20

      because i=0 corresponds to node1, i=1 to node2....... i=n-3 to node n-2.
      within the for loop, node n-2 carries address of node n-1.
      hence , at the end of the execution, temp2 stores address of node n-1.
      cheers!

    • @kanishkjain2767
      @kanishkjain2767 7 років тому +1

      how????
      for n = 1 there is a separate condition
      but for n = 2 the loop will not work because i

    • @himanshuladia9099
      @himanshuladia9099 7 років тому +1

      You actually don't want to run the loop for n=2. Because the pointer is already at n-1 that is, 1st position.,

    • @bhaveshgupta3846
      @bhaveshgupta3846 6 років тому +11

      this confusion is because he is counting the first node as 1 instead of 0.
      so if you start counting from 1 and do :
      for(i=1;inext;
      }
      you should be fine :)

    • @toxiklogic
      @toxiklogic 6 років тому +1

      Do you think this is odd? For a series on data structures in C, shouldn't we start counting at 0 for an Insert implementation?

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

    at 14:07
    shouldn't head have the value 50, instead of 150 ?

  • @dominicvarghese7993
    @dominicvarghese7993 6 років тому +1

    I could not understand the for loop used. can you explain it

  • @mycodeschool
    @mycodeschool  11 років тому +1

    Your code is not even compiling. Do not use conio.h and getch().. its not needed. And you have not written the case n==1 correctly. Check the code again.

  • @Tech.Decision100
    @Tech.Decision100 6 років тому

    Is it possible to code link list without using the pointer where only the array can be used? if it is possible to tell me how

  • @simarpreetsinghofficial
    @simarpreetsinghofficial 9 років тому +2

    +mycodeschool Sir I have written same code in c++ but when I run the program, the output is running infinitely in the output screen. Please help

    • @Ch1n4Sailor
      @Ch1n4Sailor 9 років тому +2

      +simarpreet singh
      His insert() for loop is incorrectly implemented...
      It's not moving, iterating through the n, but not moving the pointer to next node.
      it's the same as saying for(;;) { i = 0; } over & over again...
      Should be something like:
      while((node != NULL)&&(i < (n-2))) { n++; node = node->next;}
      There's also a way to do it with a for loop.

    • @omkarrajmane9408
      @omkarrajmane9408 9 років тому +1

      +simarpreet singh i too have the same problem
      this is my code..i checked with the code in video. can u plz check +mycodeschool
      #include "stdio.h"
      #include "stdlib.h"
      struct Node
      {
      int data;
      struct Node* next;
      };
      struct Node* head;
      void Insert(int data, int n)
      {
      Node* temp1=new Node(); // Dynamic memory allocation
      temp1->data=data;
      temp1->next = NULL;
      if (n == 1) // if we enter in the 1st position
      {
      temp1->next = head;
      head=temp1;
      return;
      }
      Node* temp2=head;
      for (int i = 0; i < n-2; i++)
      {
      temp2 = temp2->next;
      }
      temp1->next = temp2->next;
      temp2->next = temp1;
      }
      void Print()
      {
      Node* temp = head;
      while (temp != NULL)
      {
      printf("%d", temp->data);
      temp = temp->next;
      }printf("
      ");
      }
      void main()
      {
      head = NULL;
      printf("program begins..
      ");
      Insert(2,1);
      Insert(5, 2);
      Insert(3, 3);
      // Insert(4, 1);
      Print();
      }

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

      @@himanshuladia9099 yeah

  • @animeshnayan1
    @animeshnayan1 11 років тому

    Are you writing C or C++? In C, declare a node type as "struct Node" instead of just "Node". In C++, this will work fine.

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

    In the case for insertion at n== 1, why are we setting temp1->next = head ?

  • @VikashKumar-uh4kx
    @VikashKumar-uh4kx 5 років тому

    Shouldn't we delete the dynamically allocated memory before the function returns to avoid memory leak ?? Please suggest I am right?

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

    Sir u could go little slow, yet great explanation.

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

    how to write code to insert at the end
    i wrote this code
    void insert_end(T x)
    {
    node* temp1 = new node;
    temp1->data = x;
    temp1->next = NULL;
    if (head == NULL)
    {

    temp1->next = head;
    head = temp1;
    return;
    }

    node* temp2 = head;
    while (temp2 != NULL)
    {
    temp2 = temp2->next;
    }
    temp1->next = temp2->next;
    temp2->next = temp1;

    }
    but it gives me error derefrencing null pointer

  • @DavitJibuti
    @DavitJibuti 10 років тому +1

    can you explain, how is the last node with data "5" linked to node with data "2" , i understand how the first two node (with values 2 and 3) is linked to each other but after that i cant understand the logic. I will appreciate if you explain me this also.

    • @DavitJibuti
      @DavitJibuti 10 років тому

      mycodeschool, don't keep in mind this post, i tried to understand the logic with printing the real addresses after all step and connect them with the nodes on the paper :), and it was very helpful for me. i understand the logic :)

    • @mycodeschool
      @mycodeschool  10 років тому

      Davit Jibuti - Ok :)

  • @hemanth3687
    @hemanth3687 7 років тому

    what if after all insertions again insert (5,3) !! i m not getting it
    is the for loop inside insert wrongly implemented or it for(i=0;i

  • @mr.acholonu3519
    @mr.acholonu3519 10 років тому +1

    Can you show how this can work on a doubly linked list? I don't know how that one works.

  • @angelustt
    @angelustt 7 років тому

    what If want to make the function with 3 parameters: data, position, and a pointer to the pointer of the header?

  • @Otkucaji1
    @Otkucaji1 7 років тому +1

    Sir, thank you very much for your help, i really appreciate it

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

    best tutorial.Thanks for this.I want to know the ide u r using

  • @alenp6335
    @alenp6335 7 років тому

    great video, extremely helpful and understandable

  • @HemantKumar-dl9wh
    @HemantKumar-dl9wh 6 років тому +1

    why you take i=n-2 ?

  • @ronaldkapoor9783
    @ronaldkapoor9783 9 років тому

    What is the use of giving for loop as if the termination ends upto n-2 nly.... u have already passed only 1 or 2 value in variable n ..so always when it checks it will going to take only false value as variable i can not be less than -1(n is 1) or 0(n is 2) and for any values of I....

  • @kanishkjain2767
    @kanishkjain2767 7 років тому

    My program is running fine but i don't know how?
    (for int i=0; i

  • @mrbilalkhan
    @mrbilalkhan 7 років тому

    What is the reason that memory is not freed even though nodes are allocated memory dynamically on the heap?

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

    void InsertAtnThPosition()
    {
    int num,pos;
    Node *ptr = new Node;
    cout > num;
    cout pos;
    ptr -> data = num;
    ptr -> link = NULL;
    if (pos == 1)
    {
    ptr -> link = head; // Set the link of the new node to the node where head points
    head = ptr; // store the address of new node to be inserted at 1th position in the head node
    }
    else
    temp2 = head;
    for (int i = 0 ; i < pos -2 ; ++pos)
    {
    temp2 = temp2 -> link; // temp 2 is already pointing at first node
    }
    ptr -> link = temp2 ->link; /*sets the link of new node the next node */
    temp2 ->link = ptr; /* sets the link previous node to the new node */
    return;
    }

  • @sabbirahmed865
    @sabbirahmed865 7 років тому

    really very nice explanation.

  • @jritzeku
    @jritzeku 9 років тому +1

    why does the for loop not run for (3,2) but runs for (5,2) ??? conditions are the same are they not?

    • @kanishkjain2767
      @kanishkjain2767 7 років тому

      it will not work when n = 2 because in the the i

  • @Maririsan
    @Maririsan 9 років тому +1

    Why did you use n-2 instead of n-1 and why does it breaks when i choose n-1?

    • @ashishkapoor6257
      @ashishkapoor6257 9 років тому +3

      marvbasbas68 Their program's base is 1 instead of 0 which is by default.

  • @seewhatseeabc
    @seewhatseeabc 10 років тому +1

    This guy is good!

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

    For (i==0,inext}
    Could this be done as
    For (i==1,i