在Leetcode刷题系列java版-----链表(简单)中,主要介绍了链表的增删改查和反转链表的基本模板,
下面来看看中级题中如何运用这些模板以及一些比较有意思的题
1.
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
思路很简单,就是两个点两个点的取,然后交换即可,但是这里要自己构造一个头指针才好做,不然不太好写。这是链表题常用的技巧之一
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode root = new ListNode();
root.next = head;
ListNode r = root;
while(root.next!=null&&root.next.next!=null){
ListNode last = root.next;
ListNode next = root.next.next;
root.next = root.next.next;
last.next = next.next;
next.next = last;
root = last;
}
return r.next;
}
}
2.
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list-ii/
找到相同有重复元素就节点继续循环下去,直到该元素最后一个重复的节点,然后next改一下next指向的对象就行了
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null)return null;
ListNode root = new ListNode();
root.next = head;
ListNode r = root;
while(root.next!=null){
ListNode t = root.next;
int f=0;
while(t.next!=null&&t.val==t.next.val){//发现有重复的值就继续找下一个节点
t = t.next;
f=1;
}
if(f==1)
root.next = t.next;//此时的t.next才是要指向的点
else
root = root.next;
}
return r.next;
}
}
3.
https://leetcode-cn.com/problems/partition-list/
这题和简单篇中"2.合并两个有序链表"那题用同样的做法也能做出来,这里不多解释只贴代码做个记录
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode();
ListNode big = new ListNode();
ListNode root = small;
ListNode rootbig = big;
while(head!=null){
if(head.val
4.
https://leetcode-cn.com/problems/reorder-list/
这题的意思是整个链表收尾分别相连,两两配对,形成新的链表,L0指向Ln,L1指向Ln-1,稍微观察一下规律很容易想到可以把后半部分的链表反转,然后用两个指针,一个指向0,另一个指向n/2,这样就可以实现O(n)的复杂度快速连接配对,求出新的链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
int len=0;
ListNode root = head;
//先求出链表的长度为len
while(head!=null){
len++;
head = head.next;
}
head = root;
int step = len/2;
for(int i=0;i