C鏈表的Demo

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


typedef struct list {
	int data;
	struct list* next;
} mylist;

int printflist(mylist* list)
{
	mylist* tmp;
	tmp = list;

	printf("printf-head:     %p\n",tmp);
	printf("printf-listnode: %p\n",list);
	
	while(list)
	{
		printf("the value of list is %d.\n", list->data);
		list = list->next;
	}
}


mylist* list_reverse(mylist* head)
{
	if(head == NULL || head->next ==NULL)
		return head;

	mylist *pre = head;
	mylist *cur = head->next;
	mylist *tmp = head->next->next;
    
    while(cur)
    {
        tmp = cur->next;
        cur->next = pre;
        pre = cur;
        cur = tmp;
    }
    head->next = NULL;

	printflist(pre);
    return pre;	
}

int GetListLenght(mylist* head)
{
	int length = 0;
	mylist* current = head;

	
	if(head == NULL)
		return 0;

	while(current != NULL)
	{
		length++;
		current = current->next;
	}

	return length;
}

int mymalloc()
{
	int i = 5;

	mylist* listnode = (mylist*)malloc(sizeof(mylist));

	mylist* head = listnode;

	
	
 	while(i>0)
 	{
		mylist* tmp = (mylist*)malloc(sizeof(mylist));
		tmp->data = i;
		listnode->next = tmp;
		listnode = listnode->next;
		i--;
	}

	printf("head:     %p\n",head);
	printf("listnode: %p\n",listnode);
	printflist(head->next);
	printf("pritnode: %p\n",head->next);

	list_reverse(head->next);

}

mylist* NthfromtEnd(mylist* head, int k)
{
	mylist* pre = head, *beh = head;

	while(k > 1)
	{
		pre = pre->next;
		k--;
	}

	while(pre->next != NULL)
	{
		pre = pre->next;
		beh = beh->next;
	}

	return beh;
}

int HasCycle(mylist* head)
{
	mylist* pre = head, *beh = head;
	while(pre->next != NULL && beh->next != NULL)
	{
		pre = pre->next->next;
		beh = beh->next;

		if(pre == beh)
			return 1;
	}
		
	return 0;
	
}

mylist* deleteDuplicates(mylist* head)
{
	mylist* node_a = head;
	mylist* node_b = head->next;

	while(node_a != NULL && node_b != NULL)
	{

		if(node_a->data == node_b->data)
		{
			node_a->next = node_b->next;
			node_b = node_b->next;
		} else {
			node_a = node_b;
			node_b = node_b->next;

		}
	}

	return head;
	
}

mylist* middle_node(mylist* head)
{
	mylist* node_a = head;
	mylist* node_b = head;

	while(node_b != NULL && node_b->next != NULL)
	{
		node_a = node_a->next;
		node_b = node_b->next->next;
	}

	return node_a;
}


int main(int argc, char *argv[])
{
	mymalloc();	
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章