反转链表(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;
    }
};
全部评论

相关推荐

我已成为0offer的糕手:别惯着,胆子都是练出来的,这里认怂了,那以后被裁应届被拖工资还敢抗争?
点赞 评论 收藏
分享
点赞 1 评论
分享
牛客网
牛客企业服务