1. 递归法实现反转链表
思路:
- 递归停止的条件
- 递归调用
- 递归调用后的操作
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
//pHead->next == NULL 为递归停止的条件
if (pHead == NULL || pHead->next == NULL) {
return pHead;
}
// 递归调用
ListNode* ans = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return ans;
}
};
2. 迭代法反转链表
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pre, *cur, *nxt;
pre = NULL;
cur = pHead;
nxt = pHead;
while (cur) {
nxt = nxt->next;
cur->next = pre;
pre = cur;
cur = nxt;
}
return pre;
}
};
public ListNode ReverseList(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}