剑指offer----反转链表

题目描述
输入一个链表,反转链表后,输出新链表的表头。

//第一次遍历存储把数据压入栈,第二次遍历,数据出栈,实现反转
    ListNode* ReverseList(ListNode* pHead) {
        stack<int> stack1;
        if(pHead==NULL)return NULL;
        else if(pHead->next==NULL)return pHead;
        else
        {
            ListNode* cur=pHead;
            while(cur!=NULL)
            {
                stack1.push(cur->val);
                cur=cur->next;
            }
            cur=pHead;
            while(cur!=NULL)
            {
                cur->val=stack1.top();
                stack1.pop();
                cur=cur->next;
            }
            return pHead;
        }

    }

猜你喜欢

转载自blog.csdn.net/xiaocongcxc/article/details/82357080