solution1:
给定一个头节点为 head 的单链表用于记录一系列核心肌群训练编号,请将该系列训练编号 倒序 记录于链表并返回。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目范围是 [0, 5000]
-5000 <= Node.val <= 5000
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/7fadz7/
来源:力扣(LeetCode)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode trainningPlan(ListNode head) {
//法一链表原地逆置
// ListNode pre=null,list=head;
// while(list!=null)
// {
// ListNode node=list.next;//保存他的下一个链表节点
// list.next=pre;
// pre=list;
// list=node;
// }
// return pre;
法一内存效率不是特别好
//法二头插法,重新创建一个链表
ListNode L=new ListNode();
L.next=null;
while(head!=null)
{
ListNode p=head.next;
head.next=L.next;
L.next=head;
head=p;
}
return L.next;
}
}
//递归 传入一个当前指针的参数和前向指针
return recur(head,null);
}
public ListNode recur(ListNode cur,ListNode pre)
{
if(cur==null)return pre;
else{
ListNode res=recur(cur.next,cur);
cur.next=pre;
return res;
}
}
solution2:给定一个头节点为 head 的链表用于记录一系列核心肌群训练项目编号,请查找并返回倒数第 cnt 个训练项目编号。
示例 1:
输入:head = [2,4,7,8], cnt = 1
输出:8
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm/7f2ng5/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
public ListNode trainingPlan(ListNode head, int cnt) {
//法一先遍历多少个节点然后计算算出他的正 数是第几个元素
ListNode p=head;
int num=0;
while(p!=null)
{
num++;
p=p.next;
}
p=head;
if(num-cnt>=0)
{
for(int i=0;i<num-cnt;i++)
{
p=p.next;
}
return p;
}
else return null;
}
public ListNode trainingPlan(ListNode head, int cnt) {
//法二双指针 定义一个快指针一个慢指针它们之间的距离差cnt当快指针指向null时慢指针所指就是答案
ListNode p=head;
ListNode fast=head,slow=null;
while(fast!=null)
{
fast=fast.next;
cnt--;
if(cnt<=0)
{
if(slow==null)slow=head;
else slow=slow.next;
}
}
return slow;
}
}