如题目所示,链表的反转一般有两种方法
可以参照LeetCode题目进行观看
题目要求:反转一个链表
https://leetcode-cn.com/problems/reverse-linked-list/
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
1.双指针法
思路:1. 定以结点 pre = null; cur = head;
2.将head 后移 (head = head.next), cur 指向 pre(cur.next = pre ;) ;然后pre,cur后移到它两的下一跳(pre = cur;cur =head)
3.若head ==null;则循环结束,链表已经反转完毕。返回pre。
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode *pre=NULL;
struct ListNode*cur=head;
int Nodesum=0;
while(head!=NULL) //链表反转
{
head=head->next;
cur->next=pre;
pre=cur;
cur=head;
}
return pre;
2.递归法
满足递归的三个条件
1.大问题拆成两个子问题
2.子问题求解方式和大问题一样
3.存在最小子问题
所以能够递归;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL||head->next==NULL)
{
return head;
}
struct ListNode*p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
}
双指针点作者:水山文墨
链接:https://blog.csdn.net/qq_43411521
递归作者:tangweiqun
链接:https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/