2020.10.22每日复习
剑指Offer 24.反转链表在这里插入图片描述 **分析**
876.链表的中间节点在这里插入图片描述 **分析**
剑指Offer 24.反转链表
分析
采用双指针,令后指针元素的指针域指向前指针的元素,再令指针分别前进一位,依次类推
class Solution {
public ListNode
reverseList(ListNode head
) {
ListNode pre
= null
;
ListNode cur
= head
;
while(cur
!= null
) {
ListNode temp
= cur
.next
;
cur
.next
= pre
;
pre
= cur
;
cur
= temp
;
}
return pre
;
if(head
== null
|| head
.next
== null
) return null
;
ListNode pre
= reverseList(head
.next
);
head
.next
.next
= head
;
head
.next
= null
;
return pre
;
}
}
876.链表的中间节点
分析
采用快慢指针,快指针一次前进两个单位,慢指针前进一个单位,当快指针到头时,此时的慢指针指向的就是中间元素。
class Solution {
public ListNode
middleNode(ListNode head
) {
ListNode first
= head
;
ListNode slow
= head
;
while(first
!= null
&& first
.next
!= null
) {
first
= first
.next
.next
;
slow
= slow
.next
;
}
return slow
;
}
}