算法刷题-Day05
1. 链表的中间节点
题目描述
给定一个头结点为 head
的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
输入示例
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
注意,我们返回了一个 ListNode 类型的对象 ans,这样:
ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
思路讲解和代码实现
package com.why.day05;
/**
* @ClassName:GetNode
* @Description:todo 链表的中间结点
* @Author: why
* @DateTime:2021/11/2 17:03
*/
public class GetNode {
/**
* 返回链表的中间结点
*
* 思路:
* 1. 统计链表长度length
* 2. 定位到链表中间结点的位置
* @param head
* @return
*/
public static ListNode middleNode(ListNode head) {
ListNode temp = head;
int length = 0;
while (temp != null){
length ++;
temp = temp.next;
}
ListNode midNode = head;
if ( length%2 == 0){
int count = length / 2 + 1;
for (int i = 1; i < count; i++) {
midNode = midNode.next;
}
return midNode;
}else {
double count = length / 2 + 0.5;
for (int i = 1; i < count; i++) {
midNode = midNode.next;
}
return midNode;
}
}
}
class ListNode{
int val;
ListNode next;
}
2. 删除链表倒数第n个结点
题目描述
给你一个链表,删除链表的倒数第 n
个结点,并且返回链表的头结点。
输入示例
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
思路讲解和代码实现
package com.why.day05;
/**
* @ClassName:DeleteNode
* @Description:todo 删除链表的倒数第n个结点
* @Author: why
* @DateTime:2021/11/2 17:31
*/
public class DeleteNode {
/**
* 删除链表的倒数第n个结点
*
* 思路:
* 1. 创建pre和after指针指向链表的首部
* 2. 遍历链表,移动pre指针指向链表元素,并动态的记录length
* 3. 当length >= n+1时after指针开始移动
* 4. 当链表遍历完成时after指向的结点即为删除的前一结点
* 5. 删除结点
* 6. 返回头结点
* @param head
* @param n
* @return
*/
public static ListNode removeNthFromEnd(ListNode head, int n) {
/**
* 只有一个结点返回null
*/
if (head.next == null && n == 1){
return null;
}
ListNode pre = head;
ListNode after = null;
int length = 1;
while (pre.next != null){
pre = pre.next;
length += 1;
if (length >= n + 1){
if (length == n+1){
after = head;
}else {
after = after.next;
}
}
}
if (after == head){
after.next = head.next.next;
}else if (after == null){ //删除的结点是头节点的情况
head = head.next;
} else{
//删除结点
after.next = after.next.next;
}
return head;
}
}