题目链接:力扣
题目描述:给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
思路:遍历原链表中的每一个结点,在遍历时采用头插法插入新的链表中:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode*p=head,*xhead=new ListNode(),*q;
while(p){
q=p->next;// 保存一下 p的下一个节点,因为接下来要改变p->next
p->next=xhead->next;//头插法
xhead->next=p;
p=q;//让p等于下一个结点
}
return xhead->next;//返回新链表的第一个结点
}
};
还有另外一种方法:
双指针法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* temp; // 保存cur的下一个节点
ListNode* cur = head;
ListNode* pre = NULL;
while(cur) {
temp = cur->next; // 保存一下 cur的下一个节点,因为接下来要改变cur->next
cur->next = pre; // 翻转操作
// 更新pre 和 cur指针
pre = cur;
cur = temp;
}
return pre;
}
};
递归法:
class Solution {
public:
ListNode* reverse(ListNode* pre,ListNode* cur){
if(cur == NULL) return pre;
ListNode* temp = cur->next;
cur->next = pre;
// 可以和双指针法的代码进行对比,如下递归的写法,其实就是做了这两步
// pre = cur;
// cur = temp;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head) {
// 和双指针法初始化是一样的逻辑
// ListNode* cur = head;
// ListNode* pre = NULL;
return reverse(NULL, head);
}
};