题目描述
请编写一个函数,使其可以删除某个链表中给定的(非末尾
)节点,你将只被给定要求被删除的节点。现有一个链表– head = [4,5,1,9],它可以表示为:
4 -> 5 -> 1 -> 9
示例 1:
- 输入: head = [4,5,1,9], node = 5
- 输出: [4,1,9]
- 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
示例 2:
- 输入: head = [4,5,1,9], node = 1
- 输出: [4,5,9]
- 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
思路 1
把当前节点即(删除的节点)的下一个节点的值赋给当前节点,让当前的节点的指针指向下一个节点的next。
注意:这个思路不能删除最后一个节点。
代码 1
class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
完整代码
package cn.zcs.leetcode;
import java.io.*;
/***
*
* @author 张超帅
*
*/
class Solution237 {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}
public class deleteNode237 {
public static int[] stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if(input.length() == 0) {
return new int[0];
}
String[] inputs = input.split(",");
int[] result = new int[inputs.length];
int m = 0;
for(String i : inputs ) {
i.trim();
result[m++] = Integer.parseInt(i);
}
return result;
}
public static ListNode stringToListNode(String input) {
int[] listnodes = stringToIntegerArray(input);
ListNode dummyRoot = new ListNode(0);
ListNode ptr = dummyRoot;
for(int i : listnodes) {
ptr.next = new ListNode(i);
ptr = ptr.next;
}
return dummyRoot.next;
}
public static String ListNodeToString(ListNode head) {
if(head == null)
return "[]";
String result = "";
while(head != null) {
result += head.val + ",";
head = head.next;
}
return "[" + result.substring(0, result.length() - 1) + "]";
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
String line2;
while((line = in.readLine()) != null && (line2 = in.readLine()) != null) {
ListNode head = stringToListNode(line);
int n = Integer.parseInt(line2);
ListNode node = head;
while(node != null ) {
if(node.val == n)
break;
node = node.next;
}
new Solution237().deleteNode(node);
System.out.println(ListNodeToString(head));
}
}
}