206. 反转链表
/**
* 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 reverseList(ListNode head) {
//需要一个中间节点去保存当前修改方向的节点的下一个节点
//注意:修改指向也是修改当前不断遍历链表不断后移的节点
ListNode temp=null;
ListNode cur=null;
while(head!=null){
temp=head.next;
head.next=cur;
cur=head;
head=temp;
}
return cur;
//return head;
}
}
24. 两两交换链表中的节点
/**
* 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 swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
ListNode cur=new ListNode(0,head);
ListNode res=cur.next.next;
while(cur.next!=null &&cur.next.next!=null){
ListNode n1=cur.next;
ListNode n2=cur.next.next.next;
cur.next=cur.next.next;
cur.next.next=n1;
//n1.next=n2;
cur.next.next.next=n2;
cur=cur.next.next;
}
return res;
}
}
19. 删除链表的倒数第 N 个结点
/**
* 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 removeNthFromEnd(ListNode head, int n) {
int l=0;
ListNode temp=head;
while(temp!=null){
l++;
temp=temp.next;
}
ListNode cur=head;
if(n==l){
head=head.next;
}else{
for(int i=0;i<l-n-1;i++){
cur=cur.next;
}
cur.next=cur.next.next;
}
return head;
}
}
160. 相交链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode n1=headA;
ListNode n2=headB;
while(n1!=n2){
n1= n1==null ?headB :n1.next;
n2= n2==null ?headA :n2.next;
}
return n1;
}
}