题目描述
输入一个链表,反转链表后,输出链表的所有元素。
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;
}
ListNode* ppre = NULL;
ListNode* p = pHead;
ListNode* pnext = NULL;
while (p != NULL){
//可以整合在一起
pnext = p->next;
p->next = ppre;
ppre = p;
p = pnext;
/*
if (p == pHead){
pnext = p->next;
p->next = NULL;
ppre = p;
}
else{
pnext = p->next;
p->next = ppre;
ppre = p;
}
p = pnext;*/
}
return ppre;
}
};
2.递归
递归的实现方式主要有4步:
1)如果head为空,或者只有head这一个节点,return head即可;
2)先遍历head->next为首的链表,得到一个头结点newHead;
3)把head赋值给head->next->next, head->next为空;
4)返回newHead。
下图也说明了上述步骤:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead == NULL || pHead->next==NULL){
return pHead;
}
else{
ListNode * newHead = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return newHead;
}
}
};
类似题目
标签:head,ListNode,offer,反转,next,链表,pHead,ppre,NULL From: https://blog.51cto.com/u_15899184/5903617