forked from kexun/sort
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RemoveLastKNode.java
78 lines (64 loc) · 1.32 KB
/
RemoveLastKNode.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.demo;
/**
* 单链表中删除倒数第k个元素
* @author kexun
*
*/
public class RemoveLastKNode {
public static void main(String[] args) {
Node n1 = new RemoveLastKNode().new Node(1);
Node n2 = new RemoveLastKNode().new Node(2);
Node n3 = new RemoveLastKNode().new Node(3);
Node n4 = new RemoveLastKNode().new Node(4);
Node n5 = new RemoveLastKNode().new Node(5);
Node n6 = new RemoveLastKNode().new Node(6);
Node n7 = new RemoveLastKNode().new Node(7);
Node n8 = new RemoveLastKNode().new Node(8);
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
n5.next = n6;
n6.next = n7;
n7.next = n8;
RemoveLastKNode r = new RemoveLastKNode();
Node head = r.removeLastKNode(n1, 4);
while (head != null) {
System.out.println(head.data);
head = head.next;
}
}
public Node removeLastKNode(Node head, int k) {
if (k <= 0) {
return head;
}
if (head == null) {
return null;
}
Node curr = head;
while (curr.next != null) {
k--;
curr = curr.next;
}
if (k > 1) {
return head;
}
if (k == 1) {
return head.next;
}
curr = head;
while (k < 0) {
k++;
curr = curr.next;
}
curr.next = curr.next.next;
return head;
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
}