zhiruchen
4/15/2017 - 11:18 AM

c linked list

c linked list

#include <stdio.h>
#include <stdlib.h>

// define link list node
typedef struct node
{
	int val;
	struct node * next;
} node_t;

void print_list(node_t * head);
void push(node_t * head, int val);


int main(int argc, char const *argv[])
{
	node_t * head = NULL;
	head = malloc(sizeof(node_t));
	head->val = 1;

	head->next = malloc(sizeof(node_t));
	head->next->val = 2;
	head->next->next = NULL;

	print_list(head);
	push(head, 3);
	push(head, 4);
	push(head, 5);
	push(head, 6);
	print_list(head);

	return 0;
}

void print_list(node_t * head) {
	node_t * current = head;
	while (current != NULL) {
		printf("%d\n", current->val);
		current = current->next;
	}
}

void push(node_t * head, int val) {
	node_t * current = head;
	while (current->next != NULL) {
		current = current->next;
	}

	current->next = malloc(sizeof(node_t));
	current->next->val = val;
	current->next->next = NULL;
}