备战寒假实习,牛客刷题篇1
@TOC
一、合并两个排序的链表
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。

public class Solution {
public ListNode Merge(ListNode list1,ListNode list2) {
ListNode newHead = new ListNode(0);
ListNode head = newHead;
while(list1 != null && list2 != null) {
if(list1.val < list2.val) {
head.next = list1;
list1 = list1.next;
head = head.next;
}else {
head.next = list2;
list2 = list2.next;
head = head.next;
}
}
if(list1 != null) {
head.next = list1;
}else {
head.next = list2;
}
return newHead.next;
}
} 二、链表中倒数第k个结点
输入一个链表,输出该链表中倒数第k个结点。
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(head == null) {
return null;
}
if(k <= 0) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while(k > 0) {
if(fast == null) {
return null;
}
fast = fast.next;
k--;
}
while(fast != null) {
fast = fast.next;
slow = slow.next;
}
return slow;
}
} 三、 链表的中间结点
给定一个头结点为 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
public ListNode middleNode(ListNode head) {
ListNode fast = head;
ListNode slow = head;
if(head == null) {
return null;
}
if(head.next == null) {
return head;
}
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
} 四、 反转链表
给定一个单链表的头结点pHead(该头节点是有值的,比如在下图,它的val是1),长度为n,反转该链表后,返回新链表的表头。

public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) {
return null;
}
ListNode cur = head.next;
head.next = null;
while(cur != null) {
ListNode curNext = cur.next;
cur.next = head;
head = cur;
cur = curNext;
}
return head;
}
}
#我拿到offer啦#