笔面试算法--链表专题2(链表中的节点每k个一组翻转、链表相加)

这篇博客探讨了两个关于链表的操作:一是实现将链表逆序每k个节点一组;二是将两个链表的元素相加,形成新的链表。前者通过迭代和维护指针完成了链表的分组逆序,后者使用栈辅助实现了进位处理,有效地完成了链表节点的数值相加。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head ListNode类 
     * @param k int整型 
     * @return ListNode类
     */
    ListNode* reverseKGroup(ListNode* head, int k) {
        // write code here
        if(head==nullptr||head->next==nullptr||k<2)
            return head;
        ListNode* ft=new ListNode(-1);
        ft->next=head;
        int cd=0;
        ListNode* pre=ft;
        ListNode* now=head;
        ListNode* nex=nullptr;
        while(now!=nullptr)
        {
            cd++;
            now=now->next;
        }
        now=head;
        for(int i=1; i<=cd/k; i++)
        {
            for(int j=1; j<k; j++)
            {
                nex=now->next;
                now->next=nex->next;
                nex->next=pre->next;
                pre->next=nex;
            }
            if(i==1)
                ft->next=pre->next;
            pre=now;
            now=now->next;
        }
        return ft->next;
    }
};

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

class Solution {
public:
    /**
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    ListNode* addInList(ListNode* head1, ListNode* head2) {
        // write code here
        if(head1==nullptr)
            return head2;
        if(head2==nullptr)
            return head1;
        stack<ListNode*>s1;
        stack<ListNode*>s2;
        ListNode* p1=head1;
        ListNode* p2=head2;
        while(p1!=nullptr){
            s1.push(p1);
            p1=p1->next;
        }
        while(p2!=nullptr){
            s2.push(p2);
            p2=p2->next;
        }
        int sum=0,now=0;
        while(!s1.empty()||!s2.empty()){
            sum=now;
            if(!s1.empty()){
                sum+=s1.top()->val;
                head1=s1.top();
                s1.pop();
            }
            if(!s2.empty()){
                sum+=s2.top()->val;
                if(s2.size()>s1.size())
                    head1=s2.top();
                s2.pop();
            }
            if(sum<10){
                now=0;
                head1->val=sum;
            }
            else{
                now=sum/10;
                head1->val=sum%10;
            }
        }
        if(now>0){
            head2=new ListNode(now);
            head2->next=head1;
            return head2;
        }
        return head1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值