加一个C ++链表
假设我们有一个非负整数,表示为非空的单数位数字列表,现在我们必须在该整数上加一个。我们可以假设整数本身不包含任何前导零,除了数字0本身。在链接列表中,最高有效位在列表的开头。
因此,如果输入类似于[1,2,3],则输出将为[1,2,4]
为了解决这个问题,我们将遵循以下步骤-
如果head为null,则-
回头
curr=头
req=NULL
当curr不为零时,执行-
req:=curr
如果curr的val不等于9,则-
curr:=下一个
如果不是req为非零,则-
头部的值:=0
头:=头下
dummy=值为1的新节点
下一个假人:=头
当head不为零时,执行-
返回假人
除此以外
请求值:=0
要求:=要求的下一个
需求值增加1
要求:=要求的下一个
当req不为零时,执行-
回头
例
让我们看下面的实现以获得更好的理解。
#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int< v){
ListNode *head = new ListNode(v[0]);
for(int i = 1; i<v.size(); i++){
ListNode *ptr = head;
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
return head;
}
void print_list(ListNode *head){
ListNode *ptr = head;
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* plusOne(ListNode* head) {
if (!head)
return head;
ListNode* curr = head;
ListNode* req = NULL;
while (curr) {
if (curr->val != 9) {
req = curr;
}
curr = curr->next;
}
if (!req) {
ListNode* dummy = new ListNode(1);
dummy->next = head;
while (head) {
head->val = 0;
head = head->next;
}
return dummy;
}
else {
req->val++;
req = req->next;
while (req) {
req->val = 0;
req = req->next;
}
return head;
}
}
};
main(){
Solution ob;
vector<int< v = {1,4,5};
ListNode *head = make_list(v);
print_list(ob.plusOne(head));
}输入值
{1,4,5}输出结果
[1, 4, 6, ]