数据结构—线性结构—链表:(删除链表中倒数第n个元素)
一、题目:给定一个链表,删除链表中倒数第n个节点,返回链表的头节点。(链表中的节点个数大于n)
样例:给出链表1->2->3->4->5->null和 n = 2.
删除倒数第二个节点之后,这个链表将变成
1->2->3->5->null.
二、分析:
需要考虑的点:
1、链表只有1个元素,且n=1;如1->null,n=1;
2、删除元素为链表的头节点;
3、O(n)时间复杂度,单项链表,只走一遍;
三、代码:
**
* Definition for ListNode
*/
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public class Solution {
/**
* @param head: The first node of linked list.
* @param n: An integer
* @return: The head of linked list.
*/
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode probeNode = new ListNode(0);
ListNode currentNode = new ListNode(0);
ListNode headNode = new ListNode(0);
probeNode.next = head;
int i;
if(probeNode.next != null){
for(i = 0; i <= n; i++){
probeNode = probeNode.next;
}
currentNode.next = head;
headNode = currentNode;
while(probeNode != null){
probeNode = probeNode.next;
currentNode = currentNode.next;
}
currentNode.next = currentNode.next.next;
}else{
headNode.next = null;
}
return headNode.next;
}
}