Old Sayings

"Ngủ dậy muộn thì phí mất cả ngày, ở tuổi thanh niên mà không học tập thì phí mất cả cuộc đời." __ Ngạn ngữ Trung Quốc
"Nếu ta không gieo trồng tri thức khi còn trẻ, nó sẽ không cho ta bóng râm khi ta về già." __ Chesterfield

[Easy Data Structure] Nice functions to traverse and find middle node in Singly Linked List

#include
#include

struct ListNode * InitLinkedList();
int PrintFromBeginning(struct ListNode *head);
int CheckOddorEvenLength(struct ListNode *head);
struct ListNode *FindMiddleNode(struct ListNode *head);

//#define NULL 0
struct ListNode{
int data;
struct ListNode *next;
};

struct ListNode * InitLinkedList()
{
struct ListNode *head = malloc(sizeof(struct ListNode));
struct ListNode *node1, *node2, *node3, *node4;
struct ListNode *newNode = malloc(sizeof(struct ListNode));

node2 = malloc(sizeof(struct ListNode));
node3 = malloc(sizeof(struct ListNode));
node4 = malloc(sizeof(struct ListNode));

head->data = 1;
head->next = NULL;

node1 = head;
node1->next = node2;

node2->data = 2;
node2->next = node3;


node3->data = 3;
node3->next = node4;


node4->data = 4;
node4->next = newNode;

newNode->data = 5;
newNode->next = NULL;

return head;
}

int PrintFromBeginning(struct ListNode *head)
{
if(!head)
return 0;
else
{
printf("| %d |",head->data);
return PrintFromBeginning(head->next);
}
}

int CheckOddorEvenLength(struct ListNode *head)
{
if(!head)
return 0;
else
{
return (1 + CheckOddorEvenLength(head->next))%2;
}
}

struct ListNode *FindMiddleNode(struct ListNode *head)
{
struct ListNode *ptr1x, *ptr2x;
int i = 0;
ptr1x = ptr2x = head;
while(ptr1x->next)
{
if(i == 0)
{
ptr1x = ptr1x->next;
i = 1;
}
else
{
ptr1x = ptr1x->next;
ptr2x = ptr2x->next;
i = 0;
}
}
return ptr2x;
}
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
struct ListNode *head = InitLinkedList();
PrintFromBeginning(head);
if(CheckOddorEvenLength(head))
printf("\n-- Odd---");
else
printf("\n--- Even---");

printf("\n---Middle node: %d",FindMiddleNode(head)->data);

return 0;
}

---
Hàm cơ bản trong linked list dùng hàm đệ quy
Related Posts Plugin for WordPress, Blogger...