剑指offer15反转链表


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

/*

struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL)
            return NULL;
        if(pHead->next==NULL)
            return pHead;
        ListNode* pPre=NULL;
        ListNode* p=pHead;
        ListNode* pNext=pHead->next;
        
        ListNode* NewHead=NULL;
        while(p!=NULL)
        {
            pNext=p->next;
            if(pNext==NULL)
            {
                NewHead=p;
            }
            p->next=pPre;
            pPre=p;
            p=pNext;
        }
        return NewHead;
    }
};

猜你喜欢

转载自blog.csdn.net/u014532829/article/details/79976300