上一篇内容讲了一些简单的链表题与解法,这篇我们继续深入。(简单不意味着不重要,相反,考的就是基础)
Leecode题目序号 | 主要思路解法 |
234回文链表 | 先折半,再反转比较 |
剑指22 链表的倒数第k个节点 | 双指针 |
19删除链表的倒数第n个节点 | 快慢指针 |
83删除链表中重复的元素 | 双指针 |
234 回文链表
/*
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
要求:O(n)时间,O(1)空间
*/
class Solution {
public boolean isPalindrome(ListNode head) {
if(head==null)return true;//必须判断
ListNode firstHalfEnd = firstHalfEnd(head);
ListNode secondHalfStart = reverseList(firstHalfEnd.next);
ListNode p1 = head;
ListNode p2 = secondHalfStart;
while(p2!=null){
if(p1.val!=p2.val)return false;
p1 = p1.next;
p2 = p2.next;
}
return true;
}
public ListNode reverseList(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur!=null){
ListNode nextTemp = cur.next;
cur.next = pre;
pre = cur;
cur = nextTemp;
}return pre;
}
public ListNode firstHalfEnd(ListNode head){
ListNode fast = head;
ListNode slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}return slow;
}
}
剑指offer22——链表的倒数第k个节点
/*
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
*/
class Solution {
public ListNode getKthFromEnd(ListNode head, int k) {
ListNode cur = head;
ListNode pre = head;
int i;
for(i = 0;i<k;i++){
cur = cur.next;
}
while(cur!=null){
cur = cur.next;
pre = pre.next;
}return pre;
}
}
19 删除链表的倒数第n个节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode cur = head;
ListNode pre = head;
int i;
for(i = 0;i<n;i++){
cur = cur.next;
}
while(cur!=null){
cur = cur.next;
pre = pre.next;
}
pre.next = pre.next.next;
return head;
}
}
83 删除链表中重复的元素
class Solution {
public ListNode deleteDuplicates(ListNode head) {
ListNode current = head;
while (current != null && current.next != null) {
if (current.next.val == current.val) {
current.next = current.next.next;
} else {
current = current.next;
}
}
return head;
}
}