剑指offer---反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。
就地逆置:
/*
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=pHead;
        ListNode *q=p->next;
        ListNode *r=nullptr;
        if(q)//链表至少有两个结点
            r=q->next;
        p->next=nullptr;
        while(q){
            q->next=p;
            p=q;
            q=r;
            if(r)
                r=r->next;
        }
        pHead=p;
        return pHead;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_22238021/article/details/80667932