反转链表

你快乐吗?

Posted by bbkgl on September 26, 2019

反转链表


原地反转

Tips:链表题都可以自己先构造一个前置节点指向第一个结点,这样很多题会容易很多。。。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (!pHead) return nullptr;
        ListNode *p = new ListNode(0);
        p->next = pHead;
        pHead = p;
        p = pHead->next;
        if (p->next) {
            p = p->next;
            pHead->next->next = nullptr;
        } else return pHead->next;
        while (p) {
            ListNode *q = p->next;
            p->next = pHead->next;
            pHead->next = p;
            p = q;
        }
        return pHead->next;
    }
};