链表OJ题
1 删除链表中等于给定值 val 的所有节点。
class Solution {
public ListNode removeElements(ListNode head, int val) {
if(head==null){
return null;
}
ListNode pre=head;
ListNode cur=pre.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;
}
}
2 反转一个单链表
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode curNext=cur.next;
if(curNext==null){
head=cur;
}
cur.next=pre;
pre=cur;
cur=curNext;
}
return head;
}
}
3 给定一个带有头结点 head
的非空单链表,返回链表的中间结点
如果有两个中间结点,则返回第二个中间结点。
class Solution {
public ListNode middleNode(ListNode head) {
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;
for(int i=0;i<k-1;i++){
if(fast.next!=null){
fast=fast.next;
}else{
return null;
}
}
while(fast.next!=null){
fast=fast.next;
slow=slow.next;
}
return slow;
}
}
5 合成两个有序链表
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newHead=new ListNode(-1);
ListNode cur1=l1;
ListNode cur2=l2;
ListNode cur=newHead;
while(cur1!=null&&cur2!=null){
if(cur1.val<cur2.val){
cur.next=cur1;
cur1=cur1.next;
}else{
cur.next=cur2;
cur2=cur2.next;
}
cur=cur.next;
}
if(cur2==null){
cur.next=cur1;
}
if(cur1==null){
cur.next=cur2;
}
return newHead.next;
}
}