142. 环形链表 II
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
ListNode cur=head;
while(slow!=cur){
slow=slow.next;
cur=cur.next;
}
return cur;
}
}
return null;
}
}
237. 删除链表中的节点
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void deleteNode(ListNode node) {
ListNode cur=null;
while(node.next!=null){
ListNode node1=node.next;
cur=node;
node.val=node1.val;
node=node1;
}
//node=null
cur.next=null;
}
}
21. 合并两个有序链表
/**
* 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 ListNode mergeTwoLists(ListNode list1, ListNode list2){
//注意新创建一个链表节点的方法是 ListNode head=new ListNode(0);
// 不是ListNode head=null;
ListNode head=new ListNode(0);
ListNode cur=head;
while(list1!=null && list2!=null){
if(list1.val<list2.val){
cur.next=list1;
cur=cur.next;
list1=list1.next;
}else{
cur.next=list2;
cur=cur.next;
list2=list2.next;
}
}
if(list1==null){
cur.next=list2;
}else if(list2==null){
cur.next=list1;
}
return head.next;
}
}
2. 两数相加
/**
* 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 ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//思路不好,没有想到长度不一样时仍可采取补0解决
ListNode head=new ListNode(0);
ListNode cur=head;
int count=0;
while(l1!=null || l2!=null){
int num1= l1==null?0:l1.val;
int num2= l2==null?0:l2.val;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
int num3=num1+num2+count;
count=num3/10;
ListNode x = new ListNode(num3=num3%10);
cur.next=x;
cur=cur.next;
}
//注意:最后需要考虑是否还有进位
if(count>0){
ListNode x = new ListNode(count);
cur.next=x;
cur=cur.next;
}
return head.next;
}
}