标签:color numbers return problems sum amp number 两数相加 练习
这里来总结一下觉得比较有思想的题啪
这里的想法是a+b与b+a遍历的时间是一样的,就是说从a链表开始遍历接着从b链表开始遍历与先遍历b在遍历a同时结束。
public class Solution { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { if(headA == null || headB == null) return null; ListNode ans = null; ListNode pa = headA; ListNode pb = headB; while(pa != null || pb != null) { if(pa == null) pa = headB; if(pb == null) pb = headA; if(pa.val == pb.val && pa == pb) { ans = new ListNode(pa.val); break; } pa = pa.next; pb = pb.next; } return ans; } }
这应该是最重要最基础的操作了
递归法:
class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode temp = head; ListNode next = head.next; head = reverseList(next); next.next = temp; temp.next = null; return head; } }
头插法:
class Solution { public ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; ListNode newhead = new ListNode(-1); while(head!=null) { ListNode next = head.next; head.next = newhead.next; newhead.next = head; head = next; } return newhead.next; } }
这里有个补0的技巧,这个技巧还是蛮重要的,注意最后的进位
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode head = new ListNode(-1); ListNode p = head; ListNode p1 = l1; ListNode p2 = l2; int c = 0; int sum = 0; ListNode temp = null; while(p1!=null || p2!=null) { int o1 = p1 != null ? p1.val : 0; int o2 = p2 != null ? p2.val : 0; sum = o1 + o2 + c; c = sum/10; temp = new ListNode(sum%10); p.next = temp; p = temp; p1 = p1 == null ? null : p1.next; p2 = p2 == null ? null : p2.next; } if(c!=0) { temp = new ListNode(c); p.next = temp; } return head.next; } }
标签:color numbers return problems sum amp number 两数相加 练习
原文地址:https://www.cnblogs.com/mgblogs/p/11884570.html