题目描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
解题思路:
第一步:
第二步:
代码实现(Java语言):
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
//两次遍历解决问题
public ListNode removeNthFromEnd2(ListNode head, int n) {
if(head == null)
return null;
if(head.next == null)
return n==1?null:head;
int count = 0;
ListNode tHead = head;
while(tHead != null){
count++;
tHead = tHead.next;
}
int num = count - n;
count = 1;
tHead = head;
while(count != num){
count++;
tHead = tHead.next;
}
tHead.next = tHead.next.next;
return head;
}
//一次遍历解决问题
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode forward = head,backward = head;
for(int i=0;i<n;i++){
forward = forward.next;
}
if(forward == null){ // 走到头了,说明删除的是链表第一个元素
return head.next;
}
while(forward.next != null){
forward = forward.next;
backward = backward.next;
}
backward.next = backward.next.next;
return head;
}
}