题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路
链表的基本操作,注意传入空指针时直接返回。
Code
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == nullptr) {
return nullptr;
}
ListNode *p, *q;
p = pHead, pHead = nullptr;
while(p) {
q = p;
p = p->next;
q->next = pHead;
pHead = q;
}
return pHead;
}
};
- java
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode reverseHead = ReverseList(head.next);
head.next.next = head;
head.next = null;
return reverseHead;
}
}
总结
递归版本太妙了,一直递归到最后一个结点,然后反转,出口设计的特别棒