题解 | #反转链表#

反转链表

http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca

/*
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即可
        return pHead;
        else if(pHead->next->next==NULL)//两个节点的话也很简单,不解释了
        {
            ListNode *q=pHead;
            pHead=pHead->next;
            pHead->next=q;
            q->next=NULL;
            return pHead;
        }
        else//重点在于大于等于三个节点,此时定义两个前驱和后继指针q,p循环赋值即可改变原有链表指向
        {
            ListNode *q=pHead;
            pHead=pHead->next;
            ListNode *p=pHead->next;
            q->next=NULL;
            while(p!=NULL)
            {
                pHead->next=q;
                q=pHead;
                pHead=p;
                p=p->next;
            }
              pHead->next=q;
            return pHead;
        }
    }
};
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务