leetcode练习
876.链表的中间节点
先遍历一遍列表,记录列表的长度,得出中间列表的长度。
public ListNode middleNode(ListNode head) {
ListNode p = head;
ListNode re = p;
int i = 0;
while(p != null){
i++;
p = p.next;
}
for(int j=1;j<=i/2;j++){
re = re.next;
}
return re;
}
也可以利用快慢指针,快指针一次走两步,慢指针一次走一步,判断条件只有当q不为空且q.next不为空才有继续往下走的必要。
public ListNode middleNode(ListNode head) {
ListNode p = head, q = head;
while (q != null && q.next != null) {
q = q.next.next;
p = p.next;
}
return p;
}
19.删除链表的倒数N个元素
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode fast = head;
ListNode low = fast;
ListNode re = low;
for(int i=1; i<=n; i++){
fast = fast.next;
}
if(fast == null){
re = re.next;
return re;
}
while(fast.next != null){
fast = fast.next;
low = low.next;
}
low.next=low.next.next;
return re;
}
也可以利用递归方法
int count = 0;
public ListNode removeNthFromEnd(ListNode head, int n) {
if(head == null){
return null;
}
head.next = removeNthFromEnd(head.next,n);
count++;
if(count == n){
return head.next;
}
return head;
}