Snippets

lion 137 Clists

Created by lion 137 last modified
#include <stdio.h>

struct node {
	int data;
	struct node *next;
	};
	
struct node* buildThreeElemList(int a, int b, int c);	
struct node* push(int data, struct node* head);
int Length(struct node* head);
void printList1(int n, struct node* head);
int car(struct node* head);
struct node* cdr(struct node* head);
int isEmpty(struct node* head);

//Fun Concat
struct node* concat(struct node* head, struct node* head1);

//Main function
int main(){
	struct node* lst1 = buildThreeElemList(1, 2, 3);
	struct node* lst2 = buildThreeElemList(4, 5, 6);
	printList1(Length(lst1),lst1);
	push(7, lst1);
	printList1(Length(lst1),lst1);	

}
//End of main

struct node* buildThreeElemList(int a, int b, int c){
	struct node* head = NULL;
	struct node* second = NULL;
	struct node* third = NULL;
	head = malloc(sizeof(struct node));
	second = malloc(sizeof(struct node));
	third = malloc(sizeof(struct node));
	head->data = a;
	head->next = second;
	second->data = b;
	second->next = third; 
	third->data = c;
	third->next = NULL; 

return head;
}
	
void Push(int data, struct node** headRef) {
struct node* newNode = malloc(sizeof(struct node));
newNode->data = data;
newNode->next = *headRef; 
*headRef = newNode; 
}

int Length(struct node* head) {
struct node* current = head;
int count = 0;
while (current != NULL) {
	count++;
	current = current->next;
}
return count;
}

void printList1(int n, struct node* head){
	struct node* current = head;
	int count = 0;
	while (current != NULL) {
			count++;
			printf("lst %d = %d\n", count, current->data);
			current = current->next;
	}
}

int car(struct node* head){
	struct node* current = head;
	return current->data;
}

struct node* cdr(struct node* head){
	struct node* current = head->next;
	return current;
	}
	
int isEmpty(struct node* head){
	struct node* current = head->next;
	if(current == NULL) return 1;
		else
			return 0;
	}

/*void PushTest() {
struct node* head = BuildTwoThree();// suppose this returns the list {2, 3}
Push(&head, 1); // note the &
Push(&head, 13);
// head is now the list {13, 1, 2, 3}
}*/

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.