19. 删除链表的倒数第N个节点
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:
给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后,链表变为 1->2->3->5.
说明:
给定的 n 保证是有效的。
进阶:
你能尝试使用一趟扫描实现吗?
思路:首先循环判断有m个节点,根据倒数第n个数,得出第前 m-n个,接下来要做的是遍历获取前m-n个,为了做遍历,首先先判断第一个节点,如果为指定的节点k == 0,再next连接删除第n个节点后的节点(如果被删除后面还有节点)。
java的code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int m = 0;
ListNode temp = head;
ListNode result = null;
ListNode tempresult = null;
while(temp != null) {
temp = temp.next;
m++;
}
int k = m - n;
if(k != 0) {
result = new ListNode(head.val);
tempresult = result;
temp = head;
}else {
if(head.next != null){
result = new ListNode(head.next.val);
temp = head;
tempresult = result;
}else {
return null;
}
}
for(int i= 1; i < k ; i++) {
temp = temp.next;
tempresult.next = new ListNode(temp.val);
tempresult = tempresult.next;
}
temp = temp.next;
System.out.println(temp.val);
if(temp != null) {
tempresult.next = temp.next;
}
// while(result != null) {
// System.out.print(result.val + " ");
// result = result.next;
// }
return result;
}
}