Singly linked list various questions


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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
 #include<stdio.h>
#include<stdlib.h>
#include<conio.h>

struct node
{
    int key;
    struct node *next;
};

typedef struct node node;

void ListInit(node **head)
{
    (*head) = NULL;
}

int ListIsEmpty(node *head)
{
    return head == NULL;
}

void ListPrint(node *head)
{
    node *p = head;
    int counter = 0;
    while(p != NULL)
    {
        printf("%d -> ",p->key);
        p = p->next;
        counter++;
    }
    printf("NULL \n");
    printf("Liczba wezlow listy : %d \n",counter);
}

void ListPush(node **head,int k)
{
    node *x = (node *)malloc(sizeof(node));
    x->key = k;
    x->next = (*head);
    (*head) = x;
}

void ListPop(node **head)
{
    node *x;
    if((*head) != NULL)
    {
        x = (*head);
        (*head) = x->next;
        free(x);
    }
}

node *ListSearch(node *head,int k)
{
    node *x = head;
    while(x != NULL && x->key != k)
        x = x->next;
    return x;
}

void ListInsertNode(node **head,int k)
{
    node *x,*y,*z;
    x = (node *)malloc(sizeof(node));
    x->key = k;
    y = (*head);
    z = NULL;
    while(y != NULL && x->key > y->key)
    {
        z = y;
        y = y->next;
    }
    x->next = y;
    if(z != NULL)
        z->next = x;
    else
        (*head) = x;
}

void ListDeleteNode(node **head,int k)
{
    node *x = (*head);
    node *y = NULL;
    while(x != NULL && x->key != k)
    {
        y = x;
        x = x->next;
    }
    if((*head) != NULL && x != NULL)
    {
        if((*head) == x)
            (*head) = x->next;
        else
            y->next = x->next;
        free(x);
    }
}

void ListInsertNodeBefore(node **head,int k1,int k2)
{
    node *x = (node *)malloc(sizeof(node));
    node *y = (*head);
    node *z = NULL;
    x->key = k2;
    while(y != NULL && y->key != k1)
    {
        z = y;
        y = y->next;
    }
    x->next = y;
    if(z != NULL)
        z->next = x;
    else
        (*head) = x;
}

void ListInsertNodeAfter(node **head,int k1,int k2)
{
    node *x = (node *)malloc(sizeof(node));
    node *y = (*head);
    x->key = k2;
    while(y != NULL && y->key != k1)
        y = y->next;
    if(y != NULL)
    {
        x->next = y->next;
        y->next = x;
    }
}

void ListReverse(node **head)
{
    node *p = NULL;
    node *q = (*head);
    node *r;
    while(q != NULL)
    {
        r = q->next;
        q->next = p;
        p = q;
        q = r;
    }
    (*head) = p;
}

node *getTail(node *head)
{
    node *tail = head;
    while(tail != NULL && tail->next != NULL)
        tail = tail->next;
    return tail;
}

void tailins(node *rec,node **head,node **tail)
{
       if((*head) == NULL)
            (*head) = rec;
        else
            (*tail)->next = rec;
        (*tail) = rec;
}


node *quickSort(node *r,node **last)
{
    node *result;
    node *lowf,*lowl,*midf,*midl,*highf,*highl;

    if(r == NULL)
    {
        (*last) = NULL;
        result = r;
    }
    else
    {
        lowf = NULL;
        midf = NULL;
        highf = NULL;
        tailins(r,&midf,&midl);
        r = r->next;
        while(r != NULL)
        {
            if(r->key < midf->key)
                tailins(r,&lowf,&lowl);
            else if(r->key == midf->key)
                tailins(r,&midf,&midl);
            else
                tailins(r,&highf,&highl);
            r = r->next;
        }
        if(lowf != NULL)
        {
            lowl->next = NULL;
            result = quickSort(lowf,last);
            (*last)->next = midf;
        }
        else
            result = midf;
        if(highf != NULL)
            highl->next = NULL;
        midl->next = quickSort(highf,last);
        if((*last) == NULL)
            (*last) = midl;
    }
    return result;
}

int main()
{
    node *head, *tail,*found;
    int ch;
    int k,k1,k2;
    ListInit(&head);
    do
    {
        printf("0. Wyjdz \n");
        printf("1. Wstaw element na poczatek listy \n");
        printf("2. Usun element z poczatku listy \n");
        printf("3. Wyszukaj element na liscie \n");
        printf("4. Wstaw element w sposob uporzadkowany \n");
        printf("5. Wstaw element przed wybranym elementem \n");
        printf("6. Wstaw element za wybranym elementem \n");
        printf("7. Usun wybrany element z listy \n");
        printf("8. Posortuj liste przez podzial \n");
        printf("9. Odwroc kolejnosc elementow listy \n");
        printf("10. Wyswietl elementy listy \n");
        scanf("%d",&ch);
        switch(ch)
        {
        case 0:
            {
                while(!ListIsEmpty(head))
                    ListPop(&head);
                break;
            }
        case 1:
            {
                printf("Podaj element jaki chcesz wstawic \n");
                scanf("%d",&k);
                ListPush(&head,k);
                break;
            }
        case 2:
            {
                ListPop(&head);
                break;
            }
        case 3:
            {
                printf("Podaj element jaki chcesz wyszukac \n");
                scanf("%d",k);
                found = ListSearch(head,k);
                if(found == NULL)
                    printf("Wezla nie znaleziono na liscie \n");
                else
                    printf("Wezel znaleziono na liscie \n");
                break;
            }
        case 4:
            {
                printf("Podaj element jaki chcesz wstawic \n");
                scanf("%d",&k);
                ListInsertNode(&head,k);
                break;
            }
        case 5:
            {
                printf("Podaj element przed jakim chcesz wstawic element \n");
                scanf("%d",&k1);
                printf("Podaj element jaki chcesz wstawic \n");
                scanf("%d",&k2);
                ListInsertNodeBefore(&head,k1,k2);
                break;
            }
        case 6:
            {
                printf("Podaj element za jakim chcesz wstawic element \n");
                scanf("%d",&k1);
                printf("Podaj element jaki chcesz wstawic \n");
                scanf("%d",&k2);
                ListInsertNodeAfter(&head,k1,k2);
                break;
            }
        case 7:
            {
                printf("Podaj element jaki chcesz usunac \n");
                scanf("%d",&k);
                ListDeleteNode(&head,k);
                break;
            }
        case 8:
            {
                tail = getTail(head);
                head = quickSort(head,&tail);
                break;
            }
        case 9:
            {
                ListReverse(&head);
                break;
            }
        case 10:
            {
                ListPrint(head);
                break;
            }
        default:
                printf("Brak operacji , podaj inny numer \n");
        }

    }
    while(ch != 0);
    return 0;
}
 


Can this code be simplified f.e. by elimination extra variables
Is there memory leaks or other surprises

I would like to have void *
as data type

How can i rewrite this code to get it


If everything whith this linked list will be OK
i will try to write C++ class with these functions
malloc() returns a void*

1
2
3
4
void ListInsertNodeBefore(node **head,int k1,int k2)
{
   void *newMem = malloc(sizeof(node));
    node *x = (node *)newMem;


Its only tiny usage, but its there :)

If everything whith this linked list will be OK i will try to write C++ class with these functions
Are you aware that C++ has a std::list and std::forward_list already?

BTW your code has 2 errors + 4 warning VS 2017 CE /W4

Warning	C4477	'scanf' : format string '%d' requires an argument of type 'int *',
but variadic argument 1 has type 'int' main.cpp 255	
Warning	C4701	potentially uninitialized local variable 'lowl' used main.cpp 197
Error	C4703	potentially uninitialized local pointer variable 'lowl' used main.cpp 197	
Warning	C4701	potentially uninitialized local variable 'highl' used main.cpp 204	
Error	C4703	potentially uninitialized local pointer variable 'highl' used main.cpp 204	
Warning	C4701	potentially uninitialized local variable 'k' used main.cpp 255	


"Are you aware that C++ has a std::list and std::forward_list already?"

Yes but i would like write it just for exercise

Strange I have gcc downloaded with code::blocks ver 17.12
and quite old borland compiler and dont have these errors
gcc on ideone.com also compiled it after i had deleted line with conio. h
Yes there was & missing in line 255 and input may be other then expected
Have you any suggestions to to fix it

If we prefer merge sort than partition sort we can write it with tailins
as auxiliary function


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

node *merge(node *A,node *B)
{
      node *headS = NULL;
      node *tailS =NULL;
      while(A != NULL && B != NULL)
      {
           if(A->key <= B->key)  
           {
                  tailins(A,&headS,&tailS);
                  A = A->next;         
           }
           else
           {
                 tailins(B,&headS,&tailS);
                 B = B->next;
           }
      }
      while(A != NULL)
      {
            tailins(A,&headS,&tailS);
            A = A->next;
      }
      while(B != NULL)
      {
             tailins(N,&headS,&tailS);
             B = B->next
      }
      return headS       
}

void mergeSort(node **head)
{
    node *h1 = NULL;
    node *h2 = NULL;
    if((*head) != NULL && (*head)->next != NULL)
    {
          split((*head),&h1,&h2);
          mergeSort(&h1);
          mergeSort(&h2);
          (*head) = merge(h1,h2);
    }
}

void split(node *head,node **front,node **back)
{
/* 
   1.
         We search for the middle node which will be tail of the first sublist
         Here we have two options 
             a) left sublist can be one node shorter for odd length lists
             b) left sublist can be one node longer for odd length lists
    2.
    We  set heads for our lists which we will get after splitting
    3.
    We break the left sublist    
*/
}


How can i change the code to have void * as data type ?

Last edited on
you should not do that.
malloc returns a void * and you immediately cast it to the type you want (in c++, which probably should avoid use of malloc anyway) to cover c++'s strong typing requirements.

node* is what you want, apart from that one place where you get memory and immediately cast it back.

if you want flexibility, make node a template type that can accept a variety of types as the data that your container will store.

you might also want to move from malloc to new.
Last edited on

I asked how to write functions for the structure like this

1
2
3
4
5
struct node
{
    void  *data;
    struct node *next;
};


Now i have structure with int data type

1
2
3
4
5
struct node
{
    int  data;
    struct node *next;
};



How much differs functions to operate on these structures
Last edited on
In C you should not cast the return type from malloc.
https://bytes.com/topic/c/answers/215856-why-casting-malloc-bad-thing

So this should work.
node *x = malloc(sizeof(node));

1
2
3
4
5
struct node
{
    void  *data;
    struct node *next;
};


You could assign anything to data like to an int. The problem would be the lifetime of data which makes it dangerous.
Another option would be to add a member size to the node, allocate the memory and use them memcpy.
1
2
3
4
5
6
struct node
{
    void  *data;
    size_t data_size;
    struct node *next;
};


A way to check for memory leaks is to use functions to create and delete the nodes, where these function manage a global var node_count. At the end of the program node_count should be zero.

Manually managing memory is necessary in C, but in C++ you have much better options like the containers and smart pointers.
Topic archived. No new replies allowed.