题目来源(剑指offer):
输入一个链表,反转链表后,输出新链表的表头。递归写法
首先找到最后一个节点,设置最后一个节点为新链表的头节点,递归返回让新链表的next指向递归返回的上一层,phead=3,然后3的next指向4,4的next指向3,然后3的next指向NULL,以此类推
递归完成,链表反转成功。- 非递归
定义一个标记变量flag,令flag=cur->next,然后让cur->next=newlist,让cur的next指向newlist,再把cur的地址给newlist,newlist得到新链表的头节点,在让cur=flag继续遍历,直到找完所有,然后返回newlist
代码实现:
- 非递归
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead)
{
/*递归*/
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode*newlist=ReverseList(pHead->next);
pHead->next->next=pHead;
pHead->next=NULL;
return newlist;
/*非递归
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode*cur=pHead;
ListNode*newlist=NULL;
ListNode*flag=cur;
while(cur)
{
flag=cur->next;
cur->next=newlist;
newlist=cur;
cur=flag;
}
return newlist;
*/
}
};