#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;
}
}
//头插法反转链表
// http://c.biancheng.net/view/8105.html
mylist* list_reverse(mylist* head)
{
if(head == NULL || head->next== NULL)
{
return head;
}
mylist* new_head = NULL;
mylist* temp = NULL;
while (head)
{
temp = head;
//将 temp 从 head 中摘除
head = head->next;
//将 temp 插入到 new_head 的头部
temp->next = new_head;
new_head = temp;
}
printflist(new_head);
return new_head;
}
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;
}
C链表的Demo
于 2020-03-10 12:05:51 首次发布