Question

This is a block of code from my simple Linked List program.

void insertFirst(double dd){
        Link* pNewLink = new Link(dd);

        if (isEmpty())
            pLast = pNewLink;

        pNewLink->pNext = pFirst;
        pFirst = pNewLink;

    }

My doubt is how does Link* pNewLink = new Link(dd); works ? I know pNewLink is a pointer to the new Link Object. But I am not getting while creating a Linked List how does multiple links are created and how are they connected?

Was it helpful?

Solution

new Link(dd) statement is creating a new linked list node rather than a new list. So that, using the pFirst pointer, you replace the new node as the first node by setting its next pointer to the pFirst. After that, you overwrite the content of pFirst which was declared inside the linked list class (if it's a class).

OTHER TIPS

Here is java Implementation of LinkedList

public class SingLyLinkedList 
{
Node head = null;

static class Node {

    int data;
    Node next;

    Node(int x) {
        data = x;

    }

}

public static SingLyLinkedList insert(SingLyLinkedList list, int data) {
    Node temp = new Node(data);
    temp.next = null;

    if (list.head == null) {
        list.head = temp;

    } else {

        Node last = list.head;
        while (last.next != null) {
            last = last.next;

        }
        last.next = temp;

    }

    return list;

}

public static void printList(SingLyLinkedList list) {

    Node currNode = list.head;
    while (currNode != null) {
        System.out.print(currNode.data + "  ");
        currNode = currNode.next;

    }

}

public static void main(String[] args) {
    SingLyLinkedList ll = new SingLyLinkedList();
    ll.insert(ll, 10);
    ll.insert(ll, 20);
    ll.insert(ll, 30);
    ll.insert(ll, 40);
    printList(ll);

}}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top