1. 链表反转
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode cur = head;
ListNode prev = null;
if(cur == null){
return null;
}
while(cur != null){
ListNode curNext = cur.next;
cur.next = prev;
prev = cur;
cur = curNext;
}
return prev;//返回新的头节点
}
}
2. 删除链表中等于给定值 val 的所有节点
上一篇博客中有写到
void removeAll(int key){//删除所有指定的节点
if(this.head == null){
System.out.println("链表为空,无法进行删除");
return;
}
Node pre = this.head;
Node cur = this.head.next;
while(cur != null){
if(cur.val == key){
pre.next = cur.next;
cur = cur.next;
//this.usedSize--;
}else{
pre = cur;
cur = cur.next;
}
}
// 当链表为 441234454 时,如果先处理头节点,指定删除4,那么结果会变成 41235
if(this.head.val == key){//最后处理头节点
this.head = this.head.next;
//this.usedSize--;
}
}
3. 给定一个头结点为 head 的非空单链表,返回链表的中间结点。如果有两个中间结点,则返回第二个中间结点
力扣链接
思路:采用快慢指针
fast 每次走两步,slow 每次走一步,当 fast 为 null 时,slow 走到中间位置
class Solution {
public ListNode middleNode(ListNode head) {
if(head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}
4. 输入一个链表,输出该链表中倒数第k个结点
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k <= 0 || head == null){
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k-1 != 0){
fast = fast.next;
if(fast == null){//fast == null 表示已经走完了,如果还没找到,代表 k 超过链表长度
return null;
}
k--;
}
while(fast.next != null){
fast = fast.next;
slow = slow.next;
}
return slow;
}
}
5. 合并两个有序链表
力扣链接
将两个升序链表合并为一个新的 升序 链表并返回
新链表是通过拼接给定的两个链表的所有节点组成的
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
ListNode none = new ListNode();
ListNode tem = none;
while(list1 != null && list2 != null){
if(list1.val < list2.val){
tem.next = list1;
list1 = list1.next;
tem = tem.next;
}else{
tem.next = list2;
list2 = list2.next;
tem = tem.next;
}
}
if(list1 != null){
tem.next = list1;
}
if(list2 != null){
tem.next = list2;
}
return none.next;
}
}