-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMain19.java
More file actions
131 lines (119 loc) · 2.87 KB
/
Main19.java
File metadata and controls
131 lines (119 loc) · 2.87 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package HOT100;
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Main19 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(0,head);
int length = length(head);
ListNode cur = dummy;
for(int i=1; i<length-n+1;++i){
cur = cur.next;
}
cur.next=cur.next.next;
ListNode ans = dummy.next;
return ans;
}
public int length(ListNode head){
int length=0;
ListNode temp=head;
while (temp!=null){
length++;
temp = temp.next;
}
return length;
}
public ListNode getNode(ListNode head, int index){
if(index<1 || head==null){
return null;
}
if(index==1){
return head;
}
ListNode temp = head;
int j=1;
while (head.next!=null&&j<index){
temp=temp.next;
j++;
}
return temp;
}
public static void main(String[] args) {
}
}
class MyLink{
/**
* 向链表中插入数据
* @param d
*/
public void addNode(ListNode head,int d){
ListNode newNode = new ListNode(d);
if(head==null){
head = newNode;
}else{
ListNode temp=head;
while (temp.next!=null){
temp=temp.next;
}
temp.next=newNode;
}
}
public int length(ListNode head){
int length=0;
ListNode temp=head;
while (temp!=null){
length++;
temp = temp.next;
}
return length;
}
public ListNode getElement(ListNode head, int i){
if(i<1 || head==null){
return null;
}
if(i==1){
return head;
}
ListNode temp = head;
int j=1;
while (head.next!=null&&j<i){
temp=temp.next;
j++;
}
return temp;
}
/**
* 删除指定位置上的结点
* @param index
* @return
*/
public boolean deleteNode(ListNode head,int index){
if(index<1 || index>length(head)){
return false;
}
ListNode p = getElement(head, index-1);
ListNode q = p.next;
p.next=q.next;
return true;
}
}
class Main19_1 {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode slow = dummy, fast = dummy;
for (int i = 0; i < n ; i++) {
fast = fast.next;
}
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
slow.next = slow.next.next;
return dummy.next;
}
}