一、移除链表元素
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null)
return null;
ListNode pre=head;
ListNode cur=head.next;
while(cur!=null){
if(cur.val==val){
pre.next=cur.next;
cur=cur.next;
}
else{
pre=cur;;
cur=cur.next;
}
}
if(head.val==val){
head=head.next;
}
return head;
}
}
二、反转链表
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null)
return null;
ListNode cur=head.next;
head.next=null;
while(cur!=null){
ListNode CUR=cur.next;
cur.next=head;
head=cur;
cur=CUR;
}
return head;
}
}
三、找链表中间节点(一次循环)
class Solution {
public ListNode middleNode(ListNode head) {
if(head==null)
return null;
ListNode low=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
low=low.next;
fast=fast.next;
fast=fast.next;
}
return low;
}
}
四、输入一个链表,输出该链表中倒数第k个结点
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k<=0||head==null){
return null;
}
ListNode low=head;
ListNode fast=head;
while(k-1!=0){
fast=fast.next;
if(fast==null){
return null;
}
k--;
}
while(fast.next!=null){
low=low.next;
fast=fast.next;
}
return low;
}
}