力扣剑指offer第8天链表

24)反转链表

迭代法

class Solution{
public:
    ListNode* reverseList(ListNode* head){
        ListNode* pre = nullptr, *cur = head;
        while(cur){
            ListNode *temp = cur->next;
            cur->next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
};

递归法

class Solution{
public:
    ListNode* reverseList(ListNode* head){
        if(!head || !head->next) return head;
        ListNode *newhead = reverseList(head->next);
        head->next->next = head;
        head->next = nullptr;
        return newhead;
    }
};

25)链表中的两数相加

class Solution {
public:
    ListNode* reverseList(ListNode* l){
      if(!l || !l->next) return l;
      ListNode* newhead = reverseList(l->next);
      l->next->next = l;
      l->next = nullptr;
      return newhead;
    }
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
      l1 = reverseList(l1);
      l2 = reverseList(l2);
      ListNode *pre = nullptr;
      int carry = 0;
      while(l1!=nullptr || l2!=nullptr){
        int val = carry;
        if(l1 != nullptr){
          val += l1->val;
          l1 = l1->next;
        }
        if(l2 != nullptr){
          val += l2->val;
          l2 = l2->next;
        }
        carry = val / 10;
        val = val % 10;
        pre = new ListNode(val, pre);
      }
      if(carry) pre = new ListNode(carry, pre);
      return pre;
    }
};

26)重排链表

(z字型连接)

class Solution{
public:
    ListNode* reverseList(ListNode* l1){
        if(!l1 || !l1->next) return l1;
        ListNode* newl1 = reverseList(l1->next);
        l1->next->next = l1;
        l1->next = nullptr;
        return newl1;
    }
    void reorderList(ListNode* head){
        ListNode* dummy = new ListNode(0);
        dummy->next = head;
        ListNode* slow=dummy, *fast=dummy;
        while(fast!=nullptr && fast->next!=nullptr){
            slow = slow->next;
            fast = fast->next->next;
        }
        ListNode* headB = slow->next;
        slow->next = nullptr;
        ListNode* p1 = head;
        ListNode* p2 = reverseList(headB);
        ListNode* p3 = nullptr;
        while(p2!=nullptr){
            p3 = p1->next;
            p1->next = p2;
            p1 = p2;
            p2 = p3;
        }
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值