反转链表(C++)

反转链表

https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

方法一:利用栈实现

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        stack<ListNode*> s;
        if(pHead==NULL||pHead->next==NULL)
            return pHead;
        ListNode* p = pHead;
        while(p->next)
        {
            s.push(p);
            p = p->next;
        }
        ListNode* head = p;
        while(!s.empty())
        {
            p->next = s.top();
            p = p->next;
            s.pop();
        }
        p->next = NULL;

        return head;
    }
};

双指针法:

class Solution{
public:
    ListNode* ReverseList(ListNode* pHead)
    {
         if(pHead==NULL)
            return pHead;
        ListNode* cur = pHead;
        ListNode* pre = NULL;
        while(cur!=NULL)
        {
            ListNode* pNext = cur->next;
            cur->next = pre;
            pre = cur;
            cur = pNext;
        }   
        return pre;
    }
};
全部评论

相关推荐

Beeee0927:是缅甸园区吗
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 13:05
TMD找工作本来就烦,这东西什么素质啊😡
Beeee0927:hr是超雄了,不过也是有道理的
点赞 评论 收藏
分享
评论
点赞
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务