题目
Reverse a singly linked list.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
分析
链表转向问题,通过遍历链表,将其拆分为已经转置和待转置两部分,改变next指针即可。
/**
* 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==NULL)//假设链表为空,返回头指针
return head;
if(head->next==NULL)//假设链表只有一个元素,返回头指针
return head;
ListNode* temp_head=head->next->next;//用临时头指针保存第三个元素
head->next->next=head;//第二个元素的next指向头指针,头指针变为转置后的尾指针
ListNode* temp=head->next;//临时指针保存第二个元素
head->next=NULL;//头指针的next置为空
head=temp;//头指针恢复为第二个元素
while(temp_head!=NULL)//当需要转置的链表头指针不为空时
{
temp=temp_head->next;//临时指针保存需要转置的链表的下一节点
temp_head->next=head;//需转置头指针next指向已转置的头部
head=temp_head;//已转置头部后移
temp_head=temp;//需转置头部赋值为temp继续转置
}
return head;
}
};