力扣206—翻转链表
相关标签:递归、迭代、链表
题意
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
解法1—递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode* reverse(ListNode* pre,ListNode* cur)
{
if(nullptr==cur)
return pre;
ListNode* temp=cur->next;
cur->next=pre;
return reverse(cur,temp);
}
ListNode* reverseList(ListNode* head)
{
if(nullptr==head || nullptr==head->next)
return head;
return reverse(nullptr,head);
}
};
解法2—将后半部分链表(第一个节点之后)依次插入到第一个链表之前
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode* reverseList(ListNode* head)
{
if(nullptr==head || nullptr==head->next)
return head;
//解法2:将链表的第一个节点之后的所有节点依次插入到第一个节点之前
ListNode* cur=head->next;
head->next=nullptr;
while(cur)
{
ListNode* temp=cur->next;
cur->next=head;
head=cur;
cur=temp;
}
return head;
}
};
力扣83—删除排序链表中的重复元素
题意
解题思路
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution
{
public:
ListNode* deleteDuplicates(ListNode* head)
{
if(nullptr==head||nullptr==head->next)
return head;
ListNode* pre=head,*cur=head->next;
while(cur)
{
if(pre->val==cur->val)
{
pre->next=cur->next;
cur=cur->next;
}
else
{
pre=pre->next;
cur=cur->next;
}
}
return head;
}
};