本篇碎碎念: 无碎碎念
今日份励志文案: 很多人认为他们在思考,其实他们只是在整理自己的偏见
目录
二链表中倒数第k个结点_牛客题霸_牛客网 (nowcoder.com)
三 链表分割_牛客题霸_牛客网 (nowcoder.com)
一206. 反转链表 - 力扣(LeetCode)
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
这道题可以用递归实现也可以用循环实现(我用的是while循环) ,反转前的头节点是反转后的尾节点
class Solution {
public ListNode reverseList(ListNode head) {
if(head==null){
return head;
}
if(head.next==null){
return head;
}
ListNode reversal=null;
ListNode cur=head;
while(cur!=null){
ListNode middle=cur.next;
cur.next=reversal;
reversal=cur;
cur=middle;
}
return reversal;
}
}
二链表中倒数第k个结点_牛客题霸_牛客网 (nowcoder.com)
输入一个链表,输出该链表中倒数第k个结点。
求出总共有几个元素,如何相减求出的值
判断这个值什么时候为0,为0就返回这个值也就是倒数第k个节点
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if(k<=0||k>size(head)){
return null;
}else{
k=size(head)-k;
}
ListNode cur=head;
ListNode middle=head;
while(k>0){
cur=cur.next;
k--;
}
return cur;
}
public int size(ListNode head){
int count=0;
while(head!=null){
count++;
head=head.next;
}
return count;
}
}
三 链表分割_牛客题霸_牛客网 (nowcoder.com)
现有一链表的头指针 ListNode* pHead,给一定值x,编写一段代码将所有小于x的结点排在其余结点之前,且不能改变原来的数据顺序,返回重新排列后的链表的头指针。
public class Partition {
public ListNode partition(ListNode pHead, int x) {
// write code here
if(pHead == null) {
return null;
}
ListNode head = new ListNode(0);//虚拟头节点,方便一点
ListNode resHead = head;//返回节点
head.next = pHead;
ListNode cur = head;
ListNode pre = cur.next;
while(pre != null) {
if(pre.val < x){
if(cur == head){
pre = pre.next;
cur = cur.next;
head = cur;
}else{
ListNode tmp = pre;
cur.next = tmp.next;
tmp.next = head.next;
head.next = tmp;
head = tmp;
pre = cur.next;
}
}else{
cur = cur.next;
pre = pre.next;
}
}
return resHead.next;
}
}