每日一题之查找单链表的第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; }运行结果:
相关文章推荐
- 查找单链表的倒数第k个节点,要求只能遍历一次链表
- 链表--查找单链表的倒数第k个节点,要求只能遍历一次链表
- 逆置、翻转链表/查找单链表的倒数第k个节点/A+B不使用四则运算++ -- 等
- 反转单链表+合并有序单链表+查找单链表中倒数第k个节点--20150924
- C语言:【单链表】查找单链表的倒数第k个节点,要求只能遍历一次
- 17_7_14:逆置单链表+查找单链表的倒数第K个节点+非常规方法实现Add函数
- 查找单链表的倒数第k个节点,要求只能遍历一次链表
- C语言:【单链表】查找单链表的倒数第k个节点,要求只能遍历一次
- day02逆置/反转单链表+查找单链表的倒数第k个节点+实现一个Add函数不用四则运算
- 查找单链表的倒数第k个节点,要求只能遍历一次链表
- 逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表
- 查找单链表的倒数第k个节点
- Java单链表基本操作(五)--查找倒数第K个节点
- 查找单链表的倒数第k个节点,要求只能遍历一次链表
- 剑指offer 15---查找单链表的倒数第k个节点,要求只能遍历一次链表
- 逆置/反转单链表+查找单链表的倒数第k个节点,要求只能遍历一次链表
- 查找单链表的倒数第k个节点,要求只能遍历一次链表(C语言)
- 查找单链表倒数第K个节点和以及逆置单链表
- 查找单链表的中间节点,要求只能遍历一次链表
- 单链表中查找倒数第K个节点