文章目录
#JZ14 链表中倒数最后k个结点
描述
输入一个长度为 n 的链表,设链表中的元素的值为 ai ,输出一个链表,该输出链表包含原链表中从倒数第 k 个结点至尾节点的全部节点。
如果该链表长度小于k,请返回一个长度为 0 的链表。
示例1
输入:{1,2,3,4,5},3
返回值:{3,4,5}
思路:两个指针,一前一后,要到倒数几个数,只需要前一个指比后一个指针多几就可以了。
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param pHead ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode FindKthToTail (ListNode pHead, int k) {
int cur = 0;
ListNode first = pHead;
ListNode secord = pHead;
if(pHead == null){
return null;
}
while(cur<k && first != null){
first = first.next;
cur++;
}
while(first != null){
first = first.next;
secord = secord.next;
}
if(cur<k){
return null;
}
return secord;
}
}
#JZ16 合并两个排序的链表
描述
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1
输入:{1,3,5},{2,4,6}
返回值:{1,2,3,4,5,6}
思路:先建一个头指针,然后往后连接,依次遍历两个链表。
public class Solution {
public ListNode Merge(ListNode list1,ListNode list2){
ListNode first = list1;
ListNode second = list2;
ListNode third = new ListNode(0);
ListNode cur = third;
while(first!=null && second!=null ){
if(first.val >= second.val){
cur.next = second;
second = second.next;
}else{
cur.next = first;
first = first.next;
}
cur = cur.next;
}
while(first != null){
cur.next = first;
first = first.next;
cur = cur.next;
}
while(second != null){
cur.next = second;
second = second.next;
cur = cur.next;
}
return third.next;
}
}