Leetcode 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) {
//构建一个虚拟头节点
ListNode newHead = new ListNode(-1);
newHead.next = head;
ListNode cur = newHead;
//考虑奇数个节点和偶数个节点
while(cur.next != null && cur.next.next != null) {
ListNode a = cur.next;
ListNode b = a.next;
cur.next = b;
a.next = b.next;
b.next = a;
cur = a;
}
return newHead.next;
}
}
Leetcode 19 删除链表的倒数第 N 个结点
题目链接:删除链表的倒数第 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 size = size(head);
ListNode newHead = head;
//如果删除的是头结点
if(size == n) {
return head.next;
//如果删除的是尾结点
} else if(size == 1) {
ListNode pre = preRemove(head,n,size);
pre.next = null;
} else {
ListNode pre = preRemove(head,n,size);
pre.next = pre.next.next;
}
return newHead;
}
//找前一个结点
public static ListNode preRemove(ListNode head, int n, int size) {
int count = 0;
ListNode pre = null;
while(count != size - n - 1) {
count++;
head = head.next;
}
return head;
}
//求链表长度
public static int size(ListNode head) {
if(head == null) {
return 0;
}
int size = 0;
while(head != null) {
size++;
head = head.next;
}
return size;
}
}
Leetcode 面试02.07 链表相交
题目链接:链表相交
/**
* 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 p = headA;
ListNode q = headB;
while(p != q) {
if(p != null) {
p = p.next;
} else {
p = headB;
}
if(q != null) {
q = q.next;
} else {
q = headA;
}
}
return p;
}
}