反转链表

来源:互联网 发布:linux切换到root用户 编辑:程序博客网 时间:2024/06/15 21:54

题目描述
输入一个链表,反转链表后,输出链表的所有元素。

需要借用3个临时变量,注意边界

/*struct ListNode {    int val;    struct ListNode *next;    ListNode(int x) :            val(x), next(NULL) {    }};*/class Solution {public:    ListNode* ReverseList(ListNode* pHead) {        if(pHead==NULL||pHead->next==NULL)            return pHead;        ListNode* pre=pHead;        ListNode* cur=pHead->next;        ListNode* next=cur->next;        pHead->next=NULL;        while(next!=NULL)            {            cur->next=pre;            pre=cur;            cur=next;            next=next->next;        }        cur->next=pre;        return cur;    }};
0 0
原创粉丝点击