题目来源 | 力扣(LeetCode)
先定义ListNode类。
public class ListNode {
int val;
ListNode next;
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
public String toString() {
return "val:" + val + " next->" + next;
}
//插入链表
public void insertLinkNode(ListNode head, int val) {
ListNode p = head;
ListNode q = new ListNode();
while (true) {
if (p.next == null) {
q.setVal(val);
q.setNext(null);
p.setNext(q);
System.out.println("Insert " + val + " success.");
break;
} else {
p = p.next;
}
}
}
}
19. 删除链表的倒数第 N 个结点
给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
先计算链表长度,再用长度减去n得到需要删除的结点位置,在此结点前一个结点使用head.next = head.next.next;来做到删除操作。
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = head;
ListNode previous = head;
int len = 0;
while (dummy != null){
len++;
dummy = dummy.next;
}
if (len == n){
return previous.next;
}
for (int i = 0; i < len - n -1; i++) {
head = head.next;
}
head.next = head.next.next;
return previous;
}
}
21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
创建一个链表用于保存每次两个链表做比较后较小的结点。
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode dummy = new ListNode();
ListNode curr = dummy;
while (list1 != null && list2 != null) {
if (list1.val <= list2.val) {
curr.next = list1;
list1 = list1.next;
} else {
curr.next = list2;
list2 = list2.next;
}
curr = curr.next;
}
curr.next = list1 == null ? list2 : list1;
return dummy.next;
}
}
203.移除链表元素
给你一个链表的头节点head和一个整数val,请你删除链表中所有满足 Node.val == val 的节点,并返回新的头节点。
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode previous = dummy;
while (head != null) {
if (head.val == val) {
previous.next = head.next;
}else{
previous = previous.next;
}
head = head.next;
}
return dummy.next;
}
}
206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
class Solution {
public ListNode reverseList(ListNode head) {
ListNode dummy = new ListNode();
dummy.next = head;
while (head != null && head.next != null) {
ListNode dnext = dummy.next;
ListNode hnext = head.next;
dummy.next = head.next;
head.next = hnext.next;
hnext.next = dnext;
}
return dummy.next;
}
}
237. 删除链表中的节点
请编写一个函数,用于 删除单链表中某个特定节点 。在设计函数时需要注意,你无法访问链表的头节点 head ,只能直接访问 要被删除的节点 。
题目数据保证需要删除的节点 不是末尾节点 。
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}