(一)链表
转载链接:https://blog.csdn.net/biqioso/article/details/82951283
一、单链表逆序
单链表逆序的三种方法(递归、直接翻转指针、头插)
下文代码中的list_head 结构体为链表节点结构体
1、递归方法
struct list_head *reverse(struct list_head *head) { struct list_head *new_head; /*判断异常 || 结束判断*/ if (!head || !head->next) /*边界条件*/ return head; new_head = reverse(head->next);/*递归部分*/ head->next->next = head; /*溯回部分*/ head->next = NULL; /*记得要赋值为NULL,防止链表错乱*/ return new_head; /*返回新的链表头*/ }
2、直接翻转指针
struct list_head *reverse(struct list_head *head) { struct list_head *prev = NULL; struct list_head *next; while (head != NULL) { next = head->next; head->next = prev; prev = head; head = next; } return prev; }
3、头插法
struct list_head *reverse(struct list_head *head) { struct list_head *z, *save_next; save_next = head->next; /*j用来保存下一个要翻转的结点*/ head->next = NULL; /*这里相当于把链表头与链表的其余\ 部分断开,作为新的链表头*/ while (save_next != NULL) { z = save_next; save_next = save_next->next; z->next = head->next; head->next = z; } return head; }
二、求链表的中间节点
转自链接:https://blog.csdn.net/biqioso/article/details/83005096
求链表的中间节点(利用快慢指针)
①链表有奇数个节点时,中间节点只有一个;
②链表偶数个节点时,结果为输出节点和它的下一个!
struct list_head *find_mid(struct list_head *head) { struct list_head *slow, *fast; slow = head; /*快慢指针都指向第一个节点*/ fast = head; while (fast != NULL && fast->next != NULL && fast->next->next != NULL) { slow = slow->next; /*慢指针每次走一步*/ fast = fast->next->next; /*快指针每次走两步*/ } return slow; }
这是我的博客,喜欢技术,喜欢头脑风暴,欢迎交流
博客园:https://www.cnblogs.com/live-passion/ CSDN博客:https://blog.csdn.net/weixin_43960484