Last updated on 2023年9月23日 下午
2. 两数相加(Java实现)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode p1 = l1; ListNode p2 = l2; ListNode newHead = new ListNode(0); ListNode resultHead = newHead;
int curr = 0; int jin = 0;
while(p1 != null && p2 != null){ curr = (p1.val + p2.val + jin) % 10; ListNode tmp = new ListNode(curr); newHead.next = tmp; newHead = newHead.next;
jin = (p1.val + p2.val + jin) / 10;
p1 = p1.next; p2 = p2.next; }
while(p1 != null){ curr = (p1.val + jin) % 10; jin = (p1.val + jin) / 10; ListNode tmp = new ListNode(curr); newHead.next = tmp; newHead = newHead.next;
p1 = p1.next; }
while(p2 != null){ curr = (p2.val + jin) % 10; jin = (p2.val + jin) / 10;
ListNode tmp = new ListNode(curr); newHead.next = tmp; newHead = newHead.next;
p2 = p2.next; }
if(jin != 0){ ListNode tmp = new ListNode(jin); newHead.next = tmp; newHead = newHead.next; }
return resultHead.next; } }
|
19. 删除链表的倒数第 N 个结点(Java实现)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode dummy = new ListNode(0); dummy.next = head;
ListNode slow = dummy; ListNode fast = dummy;
for(int i = 0;i <= n;i++){ fast = fast.next; }
while(fast != null){ slow = slow.next; fast = fast.next; }
slow.next = slow.next.next;
return dummy.next; } }
|
24. 两两交换链表中的节点(Java实现)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
class Solution { public ListNode swapPairs(ListNode head) { ListNode resultNode = new ListNode(0); resultNode.next = head; ListNode curr = resultNode;
while(curr.next != null && curr.next.next != null){ ListNode slowTmp = curr.next; ListNode fastTmp = curr.next.next.next;
curr.next = curr.next.next; curr.next.next = slowTmp; curr.next.next.next = fastTmp;
curr = curr.next.next;
}
return resultNode.next; } }
|
leetcode-hot-100-20230922
https://thewangyang.github.io/2023/09/22/leetcode-hot-100-20230922/