C++单向链表按顺序插入输出

这篇文章是在刷力扣的有关链表算法题有感而发

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        int i = 0, j = 0,num = 0;
        bool max10 = false, isFirst = true;
        int temp = 0;
        ListNode * head = new ListNode();
        ListNode * ss = head;
        while(l1 != NULL || l2 != NULL || max10){
            i = 0; j = 0; temp = 0;
            if(l1 != NULL){
                i = l1->val;
                l1 = l1->next;
            }
            if(l2 != NULL){
                j = l2->val;
                l2 = l2->next;
            }
            temp = i + j;
            if(max10){
                temp++;
                max10 = false;
            }
            if( temp >= 10){
                max10 = true;
                temp -= 10;
            }
            if(isFirst){
                head->val = temp;
                isFirst = false;
            }else{
                ListNode * test = new ListNode(temp);
                ss->next = test;
                ss = ss->next;
            }
        }
        return head;
    }
};

 如代码所示

ListNode * head = new ListNode(); //创建链表第一个结点(头节点)

ListNode * ss = head;//通过一个临时的链表节点指向头节点

ListNode * test = new ListNode(temp);

ss->next = test;

ss = ss->next;

后续对这个单向链表的操作都通过这个临时的头节点去操作,然后在函数返回的时候返回head(初始头节点)的方式从而达到返回链表头的效果,有感而发,有错误或者更加方便的方法敬请大家指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值