链表反转java,两数之和,整数反转

遍历法求链表翻转

1、链表为空,返回头节点

2、定义两个结点 pre 为 null ,cur指向头节点

3、遍历链表时,定义临时结点存放 cur 的下一结点,同时让 cur 指向 pre

4、因为要向后遍历,pre 向后移到 cur 的位置,cur 移到刚刚定义的临时结点位置 (达到链表反转效果) …(以此循环)

5、最后因 cur == null 跳出循环, pre 在cur 的前一位,所以返回 pre 即可

class Solution {
          
   
    public ListNode reverseList(ListNode head) {
          
   
        if (head == null) return head;
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
          
   
            ListNode temp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
        return pre;
    }
}

两数之和:

js实现:暴力求解:

var twoSum = function(nums, target) {
          
   
    for(let i=0;i<nums.length;i++){
          
   
            for( let j=i+1;j<nums.length;j++){
          
   
                if(nums[i]+nums[j]==target){
          
   
              
               return [i,j]
                
                }
            }
        }

};

整数反转:

class Solution {
          
   
    public int reverse(int x) {
          
   
    long res=0;
    while(x!=0){
          
   
        res=res*10+x%10;
        x/=10;
    }
    if((int)res==res){
          
   
        return (int)res;
    }else{
          
   
        return 0;
    }
    }
}
经验分享 程序员 微信小程序 职场和发展