單向鏈表

題目描敘:

You are given two non-empty linked lists representing two non-negative integers.
The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
簡單描敘題目意思:
給出了兩個非空鏈表,數(shù)據(jù)為非負整數(shù)。鏈表倒敘,再相加,逢10進1
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

//Definition for singly-linked list.
 function ListNode(val) {
     this.val = val;
     this.next = null;
 }
 
 /**
  * @param {ListNode} l1
  * @param {ListNode} l2
  * @return {ListNode}
  */
 var addTwoNumbers = function(l1, l2) {
   var sum = l1.val + l2.val;
   var lFirst = new ListNode(sum%10);
   var arg = sum>=10 ? 1 : 0
   var lPrev = lFirst
   l1 = l1.next
   l2 = l2.next;
   while(l1!==null || l2!==null){
     var v1 = l1 === null ? 0: l1.val
     var v2 = l2 === null ? 0: l2.val
     sum = v1+ v2+ arg
     var lMiddle = new ListNode(sum%10)
     arg = sum>=10 ? 1 : 0
     lPrev.next = lMiddle
     lPrev = lMiddle
     if (l1 !== null) l1 = l1.next;
     if (l2 !== null) l2 = l2.next;
   }
   if(arg>0){
     lMiddle = new ListNode(1);
     lPrev.next = lMiddle
   }
   return lFirst
 };

 var a1 = new ListNode(2);
 var a2 = new ListNode(4);
 var a3 = new ListNode(3);
 a1.next = a2;
 a2.next = a3;

 var b1 = new ListNode(5);
 var b2 = new ListNode(6);
 var b3 = new ListNode(4);
 b1.next = b2;
 b2.next = b3;

 var s = addTwoNumbers(a1, b1);
 console.log(s)

單項鏈表 A->B->C->D->E , 輸出 E->D->C->B->A

初始化數(shù)據(jù)a1

ffunction ListNode(val) {
    this.val = val;
    this.next = null;
    return {
      val:val,
      next:null
    }
}

var a1 = new ListNode('A')
var a2 = new ListNode('B')
var a3 = new ListNode('C')
var a4 = new ListNode('D')
var a5 = new ListNode('E')
a1.next = a2
a2.next = a3
a3.next = a4
a4.next = a5
1 思路

把當(dāng)前鏈表的下一個節(jié)點pCur插入到頭結(jié)點dummy的下一個節(jié)點中,就地反轉(zhuǎn)。
dummy->A->B->C->D->E
dummy->B->A->C->D->E
dummy->C->B->A->D->E
dummy->D->C->B->A->E
dummy->E->D->C->B->A

2 過程

pCur是需要反轉(zhuǎn)的節(jié)點。
prev連接下一次需要反轉(zhuǎn)的節(jié)點
反轉(zhuǎn)節(jié)點pCur
糾正頭結(jié)點dummy的指向
pCur指向下一次要反轉(zhuǎn)的節(jié)點

偽代碼
prev.next = pCur.next;
pCur.next = dummy.next;
dummy.next = pCur;
pCur = prev.next;
function reverse(list){
  if(list == null){
    return list
  }
  var dummy = ListNode(-1);
  dummy.next = list;
  var prev = dummy.next;
  var pCur = prev.next;
  while(pCur !==null){
    prev.next = pCur.next;
    pCur.next = dummy.next;
    dummy.next = pCur;
    pCur = prev.next;
  }
  return dummy.next
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容