兩數相加
考慮創建啞節點dummy,使用dummy->next表示真正的頭節點,避免空邊界. 時間複雜度
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* first = new ListNode(0); // 啞結點
ListNode* last = first;
int carry = 0;
while(l1 or l2 or carry){
// 相加
int bitsum = 0;
if(l1){
bitsum += l1->val;
l1 = l1->next;
}
if(l2){
bitsum += l2->val;
l2 = l2->next;
}
if(carry){
bitsum += carry;
}
// 結果
int digit = bitsum % 10;
carry = bitsum / 10;
// 鏈表存儲
ListNode* node = new ListNode(digit);
last->next = node;
last = node;
}
last = first->next;
delete first;
return last;
}
};
反轉鏈表輸出
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
方法一:使用std::reverse()
反轉鏈表的輸出vector
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
std::vector<int> ret;
while(head!=nullptr){
ret.push_back(head->val);
head= head->next;
}
//再開闢內存,逆序遍歷
//for(auto iter=arr.rbegin(); iter<arr.rend();iter++){
// ret.push_back(*iter);
//}
std::reverse(ret.begin(), ret.end());
return ret;
}
};
方法二:直接反轉鏈表,改變指針指向
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
ListNode* newHead = nullptr;
ListNode* node; // 存放刪除的結點,也是新插入的結點
while(head){
node = head; // 保存刪除
head = head->next; // 更新頭
node->next = newHead; // 重新插入
newHead = node; // 更新頭
}
std::vector<int> ret;
while(newHead){
ret.push_back(newHead->val);
newHead = newHead->next;
}
return ret;
}
};