206. Reverse Linked List

题目

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;
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值