203,移除链表元素
203,移除链表元素
2.两数之和
package 链表;
/**
* https://leetcode-cn.com/problems/add-two-numbers/
*
* @author MJ
*
*/
public class _0002_两数相加 {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummyHead = new ListNode(0);
ListNode last = dummyHead;
// 进位值
int carry = 0;
while (l1 != null || l2 != null) {
int v1 = 0;
if (l1 != null) {
v1 = l1.val;
l1 = l1.next;
}
int v2 = 0;
if (l2 != null) {
v2 = l2.val;
l2 = l2.next;
}
int sum = v1 + v2 + carry;
// 设置进位值
carry = sum / 10;
// sum的个位数作为新节点的值
last.next = new ListNode(sum % 10);
last = last.next;
}
// 检查最后的进位
if (carry > 0) {
// carry == 1
last.next = new ListNode(carry);
}
return dummyHead.next;
}
}
160.相交链表
86.分隔链表
package 链表;
/**
* https://leetcode-cn.com/problems/partition-list/
*
* @author MJ
*
*/
public class _0086_分隔链表 {
public ListNode partition(ListNode head, int x) {
if (head == null) return null;
ListNode lHead = new ListNode(0);
ListNode lTail = lHead;
ListNode rHead = new ListNode(0);
ListNode rTail = rHead;
while (head != null) {
if (head.val < x) { // 放在lTail后面
lTail.next = head;
lTail = head;
} else { // 放在rTail后面
rTail.next = head;
rTail = head;
}
head = head.next;
}
// 这句代码不能少
/*
* 因为可能出现这样的情况:
* 原链表倒数第N个节点A的值是>=x的,A后面所有节点的值都是<x的
* 然后rTail.next最终其实就是A.next
*/
rTail.next = null;
// 将rHead.next拼接在lTail后面
lTail.next = rHead.next;
return lHead.next;
}
}
234.回文链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head == null || head.next == null) return true;
if(head.next.next == null) return head.val == head.next.val;
//找到中间结点
ListNode mid = middleListNode(head);
//翻转右半部分(中间结点的右半部分)
ListNode rHead = reverseList(mid.next);
ListNode lHead = head;
//从lHead,rHead触发,判断是否为回文链表
while(rHead != null){
if(lHead.val != rHead.val) return false;
rHead = rHead.next;
lHead = lHead.next;
}
return true;
}
//用快慢指针找到中间结点
private ListNode middleListNode(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
private ListNode reverseList(ListNode head){
ListNode newHead = null;
while(head != null){
ListNode tmp = head.next;
head.next = newHead;
newHead = head;
head = tmp;
}
return newHead;
}
}