algoritmauzmanı
TREN
3.1Singly Linked List
Lesson 3.1.2

Creating a singly linked list

In What is a singly linked list? you saw what a looks like. Now we build a small list by hand: 12 → 7 → 3. This lesson is the starting point of every list operation; the drawings in the following lessons all start from this list.

What you will learn
  • How memory is allocated for the nodes and how the values are written
  • In which order the nodes are linked through their fields
  • Why the last node must point to and why is set to the first node
6 minTime O(n)Memory O(n)C · Java · Python

1Idea

Building a linked list takes three jobs. First, memory is allocated for each and its value is written. Then the address of the following node is written into each node's field. Finally is pointed at the first node.

In C, memory comes from and the node is defined as a . In Java and Python, writing new Node(12) or Node(12) both allocates the memory and writes the value. In those two languages the next field already starts as null or None; in C it holds an unknown value, so NULL is written into the last node's next field explicitly.

Before the list is built, head points to . That is the empty list: there are no nodes and head points nowhere.

2Step by step

The drawing allocates three nodes holding 12, 7 and 3, links them together and sets head to the first node. At each step the matching line of code lights up.

12?0x1a407?0x1a903?0x1b20head = NULLfirstsecondthird
  1. Start. There are no nodes yet; points to . The list is empty.
  2. Memory is allocated for three nodes and their values are written: 12, 7 and 3. The nodes sit in separate places in memory with no links between them yet. Their next fields are unknown.
  3. first->next = second: the node holding 12 now points to 7.
  4. second->next = third: the node holding 7 points to 3. The chain grows.
  5. is written into the last node's field. Code that walks () the list knows from this value where to stop.
  6. is set to the first node. From now on the list is always reached through head.
  7. Result: 12 → 7 → 3 → NULL. The helper variables (first, second, third) are no longer needed; the list is held by head.

struct Node {    int data;    struct Node* next;}; void createList(struct Node** head) {    struct Node* first = malloc(sizeof(struct Node));    struct Node* second = malloc(sizeof(struct Node));    struct Node* third = malloc(sizeof(struct Node));    first->data = 12;    second->data = 7;    third->data = 3;    first->next = second;    second->next = third;    third->next = NULL;   // last node    *head = first;}
class Node {    int data;    Node next;    Node(int data) { this.data = data; }} Node createList() {    Node first = new Node(12);    Node second = new Node(7);    Node third = new Node(3);    first.next = second;    second.next = third;    third.next = null;   // last node (already null)    Node head = first;    return head;}
class Node:    def __init__(self, data):        self.data = data        self.next = None def create_list():    first = Node(12)    second = Node(7)    third = Node(3)    first.next = second    second.next = third    third.next = None  # last node (already None)    head = first    return head

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

For a list of n nodes, each node takes one allocation and one link assignment. In this example n = 3.

Memory
O(n)

Each node takes room for one value and one pointer. Memory grows in proportion to the number of nodes.

Real programs do not write the nodes out one by one; they call insert at the head or insert at the end inside a loop.

4Common mistake

The most common mistake in C is leaving the last node's next field unset:

struct Node* third = malloc(sizeof(struct Node));third->data = 3;// third->next = NULL; is missing

does not clear the memory. A random address stays in next, and code that walks the list jumps to that address and crashes or reads garbage. Always write into the last node's next field.

5Try it

You allocated and linked three nodes but forgot the line head = first. What state is the list in?

Show the answer

The answer is A. Until is set there is no way to reach the list from outside. When the function returns, the helper variables are gone too, and the nodes stay in memory with nothing pointing to them.

Does the order of linking matter? What if you write second->next = third first and then first->next = second?

Show the answer

The answer is B. Here every node's address lives in its own variable, so the links can be set in any order. Adding to an existing list is different; when inserting at a position the order matters.

Lessons you mark show up in the curriculum. This is kept on this device only.