题目其实很简单,数据结构的时候就学了,但是现在写下来就是想记录一下大佬的递归写法,感觉很多时候,递归其实是解决链表问题的一种很好的思路,但是自己总是忘掉。
1非递归写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
ListNode* head0 = new ListNode(0),*cur =head;
head0->next = head;
ListNode* pre =head0;
while(cur){
if(cur->val == val){
pre->next = cur->next;
break;
}
pre = pre->next;
cur = cur->next;
}
return head0->next;
}
};
2、递归写法
class Solution {
public:
ListNode* deleteNode(ListNode* head, int val) {
if(!head) return NULL;
if(head->val == val) return head->next;
head->next = deleteNode(head->next,val);
return head;
}
};
有一道题目感觉思路和这个大致相同哎,剑指offer25,合并两个排序的链表,同样是递归的思路,也相对来说很好理解。
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(l1==nullptr) return l2;
if(l2==nullptr) return l1;
if(l1->val<l2->val){
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}else{
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};