剑指offer面试题16
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
分析:
头结点存储数据。
已知链表:
pReverseHead为最终反转后的链表头指针:
注意要给pReverseHead->next设置为NULL,否则pReverseHead后面等于pHead所含结点
改变指针指向的具体操作:
第一次改变指针指向后:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//头指针为NULL 或者 链表为空
if(pHead == NULL || pHead->next == NULL)
{
return pHead;
}
ListNode *p = pHead->next;
ListNode *p1 = NULL;
ListNode *pReversHead = pHead;
pReversHead->next = NULL;
while(p != NULL)
{
p1 = p->next;
p->next = pReversHead;
pReversHead = p;
p = p1;
}
return pReversHead;
}
};