Post

[LeetCode] Implementing a Singly Linked List in C

Data Structure

  • Books : C언어로 설명하는 자료구조 프로그래밍

Single Linekd List

1. Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stdio.h>
#include <stdlib.h>

// define the node structure
struct node {
    int num;
  struct node *next;
};

// create a new node
struct node* createNode(int num) {
  struct node* newNode = (struct node*)malloc(sizeof(struct node));
  newNode->num = num;
  newNode->next = NULL;
  return newNode;
}

// to append a node to the end of the linked list
void appendNode(struct node** head, int num) {
  struct node* newNode = createNode(num);
  if (*head == NULL) {
    *head = newNode;
  } else {
    struct node* temp = *head;
    while (temp->next != NULL) {
      temp = temp->next;
    }
    temp->next = newNode;
  }
}

// to traverse the linked list and print each node's data
void printList(struct node* head) {
  struct node* temp = head;
  while (temp != NULL) {
    printf("%d -> ", temp->num);
    temp = temp->next;
  }
  printf("NULL\n");
}

int main() {
  struct node* head = NULL;  // Head pointer (the start of the linked list)

  appendNode(&head, 1);  // Add nodes to the list
  appendNode(&head, 2);
  appendNode(&head, 3);

  printList(head);

  // deallocation
  while (head != NULL) {
    struct node* temp = head;
    head = head->next;
    free(temp);
  }

  return 0;
}
This post is licensed under CC BY 4.0 by the author.