输入一个链表,反转链表后,输出新链表的表头。
示例1
输入
复制
{1,2,3}
返回值
复制
{3,2,1}
解:链表反转,实质就是将链表各个结点的指针反转,可以想象链表的反转实现需要借助三个指针来实现,各自相邻指向具体的结点。实现过程如下:
/*
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 *p = NULL, *q = NULL, *r = NULL;
p = pHead;
q = pHead -> next;
while(q -> next != NULL)
{
r = q -> next;
q -> next = p;
p = q;
q = r;
}
q -> next = p;
pHead -> next = NULL;
pHead = q;
return pHead;
}
};