赞
踩
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
思路:
使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点,记作 ret。此后,每次函数在返回的过程中,让当前结点的下一个结点的 next 指针指向当前节点。同时让当前结点的next 指针指向 NULL,从而实现从链表尾部开始的局部反转。
递归。详细讲解的视频
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { if(head==nullptr || head->next==nullptr){ return head; } ListNode* p=reverseList(head->next); //处理head->next为头的链表 //处理当前head节点 head->next->next=head; head->next=nullptr; return p; } };
迭代
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* cur = NULL, *pre = head; //返回cur while (pre != NULL) { ListNode* tmp=pre->next; pre->next = cur; cur = pre; pre = tmp; } return cur; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。