JZ15
輸入一個連結串列,反轉連結串列後,輸出新連結串列的表頭。
示例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;
}
};