สมมติว่ามีจำนวนเต็มบวกหรือศูนย์ที่แทนด้วย singly linked list ของหลักเลขที่ไม่ว่างเปล่า ตอนนี้เราต้องบวกหนึ่งให้กับจำนวนเต็มนั้น เราสามารถสมมติได้ว่าจำนวนเต็มไม่มีศูนย์นำหน้า ยกเว้นตัวเลข 0 เอง ใน linked list หลักเลขที่สำคัญที่สุดอยู่ที่หัวของลิสต์
เช่น ถ้าอินพุทเป็น [1,2,3] ผลลัพธ์จะเป็น [1,2,4]
เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนดังนี้ −
ถ้า head เป็น null แล้ว −
คืนค่า head
curr = head
req = NULL
ลูป while curr ไม่เป็นศูนย์ ทำ −
ถ้าค่าของ curr ไม่เท่ากับ 9 แล้ว −
req := curr
curr := next ของ curr
ถ้า req ไม่เป็น non-zero แล้ว −
dummy = โหนดใหม่ค่า 1
next ของ dummy := head
ลูป while head ไม่เป็นศูนย์ ทำ −
ค่าของ head := 0
head := next ของ head
คืนค่า dummy
มิฉะนั้น
เพิ่มค่าของ req ขึ้น 1
req := next ของ req
ลูป while req ไม่เป็นศูนย์ ทำ −
ค่าของ req := 0
req := next ของ req
คืนค่า head
ตัวอย่าง
ลองดูการติดตั้งต่อไปนี้เพื่อให้เข้าใจได้ดีขึ้น
#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, ]