力扣——链表篇
移除链表元素
203.给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
思路:借助一个虚拟的头结点,进行链表的遍历找到与目标数,将当前指针指向当前指针的下一个节点的下一个节点,就可以实现删除操作。
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head == null){
return head;
}
ListNode node = new ListNode(0,head);
ListNode temp = node.next;
while(temp.next != null){
if(temp.next.val == val){
temp.next = temp.next.next;
}else{
temp = temp.next;
}
}
return node.next;
}
}
翻转链表
206.给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
思路:进行一次遍历,将当前节点变成下一个节点的下一个节点即可,也就是指针指向的方向与之前相反就可以实现链表的翻转。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null,temp = null;
ListNode cur = head;
while(cur != null){
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
两两交换链表中的节点
24.给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode newHead = new ListNode(0);
newHead.next = head;
ListNode pre = newHead;
while(pre.next != null && pre.next.next != null){
ListNode temp = head.next.next;
pre.next = head.next;
head.next.next = head;
head.next = temp;
pre = head;
head = head.next;
}
return newHead.next;
}
}
删除链表倒数第n个
19.给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode newHead = new ListNode(0,head);
ListNode cur = newHead;
int count = 0;
while(cur.next != null){
cur = cur.next;
count++;
}
cur = newHead;
for(int i=0;i<count-n;i++){
cur = cur.next;
}
cur.next = cur.next.next;
return newHead.next;
}
}
链表相交
02.07给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode A = headA;
ListNode B = headB;
while(A != B){
A = A != null ? A.next : headA;
B = B != null ? B.next : headB;
}
return A;
}
}
环形链表
142.给定一个链表的头节点 head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。
不允许修改 链表。
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode slow = head, fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow){
ListNode index1 = fast;
ListNode index2 = head;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}