您的位置:首页 > 其它

每日一题之查找单链表的第K个节点

2017-07-17 17:53 106 查看
逆置/反转单链表+查找单链表的第K个节点,要求只能便利一次链表。

#include<stdio.h>
#include<malloc.h>

typedef int Datatype;
typedef struct node
{
Datatype data;
struct node *next;
}LinkedNode, *LinkList;

LinkList create_list()
{
Datatype value[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int len = sizeof(value) / sizeof(Datatype);
int i = 0;
LinkedNode *list_head = NULL;
LinkedNode *tmp = NULL;
LinkedNode *p = NULL;

list_head = (LinkedNode*)malloc(sizeof(LinkedNode));
list_head->data = value[0];
list_head->next = NULL;

tmp = list_head;
for (i = 1; i < len; i++)
{
while (tmp->next != NULL)
{
tmp=tmp->next;
}
p = (LinkedNode*)malloc(sizeof(LinkedNode));
p->data = value[i];
p->next = NULL;
tmp->next = p;
}
return list_head;
}
void Print(LinkList list)
{
LinkedNode *tmp = NULL;
if (list == NULL)
{
return;
}
tmp = list;
while (tmp != NULL)
{
printf("%d", tmp->data);
tmp = tmp->next;
}
printf("\n");
return;
}
void reverse_list(LinkList list)
{
LinkedNode *pre = list;
LinkedNode *cur = list->next;
LinkedNode *next = NULL;

if (list == NULL || list->next == NULL)
return;

/*在这里实现翻转*/
while (cur != NULL)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
list->next = NULL;
list = pre;
Print(list);
return;
}

void reverse_the_list(LinkedNode *cur, LinkList *list)
{
LinkedNode *next = NULL;
if (cur == NULL || cur->next == NULL)
{
*list = cur;
}
else
{
next = cur->next;
reverse_the_list(next, list);
next->next = cur;
cur->next = NULL;
}
return;
}

int main()
{
LinkList list = NULL;
LinkedNode *temp = NULL;
LinkList list2 = NULL;

list = create_list();
Print(list);
reverse_list(list);

list2 = create_list();
temp = list2;
reverse_the_list(temp, &list2);
Print(list2);
system("pasue");
return 0;
}
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐