滑动窗口
利用迭代的思想,每次循环会得到尾数last,并将传入的num利用/将范围缩小——>因为是倒序我们可以利用结果集*10+last得到最后的结果集
public int reverse(int num){
int result=0;
while(num!=0){
if(result<Integer.MIN_VALUE/10||result>Integer.MAX_VALUE/10){
return 0;
}
//关键
int last = num % 10;
num/=10;
result=result*10+last;
}
return result;
}
虚拟一个头节点,然后每进一次循环定义一个next后继节点,然后对当前节点进行操作——>cur.next=pre ,pre=cur, cur=next返回pre即可
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
//滑动窗口
while (cur != null) {
//1.当前节点下一个节点
ListNode next = cur.next;
//2,cur指向前面一个节点开始倒叙
cur.next = pre;
//3,pre前进一步
pre = cur;
//4.cur前一步
cur = next;
}
return pre;
}
递归解决反转链表
剑指 Offer 24. 反转链表 - 力扣(LeetCode)
1.首先确立base,head.next==null||head==null——>2.进入递归框架直至最后一个节点node(我们这里利用后序的思想)——>3.node只是当前方法中递归返回的节点,也就是个末尾节点——>4.我们利用当前head.next.next=head进行调换位置,当前节点head=null,返回node
public ListNode reverseList(ListNode head){
//1.base
if(head==null||head.next==null){
return head;
}
//2.递归框架
ListNode node= reverseList(head.next);
//3.后序位置处理反转逻辑
head.next.next=head;//两节点指向交换
head.next=null;
return node;
}