LeetCode【237.删除表中的节点】

题目描述

请编写一个函数,使其可以删除某个链表中给定的(非末尾)节点,你将只被给定要求被删除的节点。现有一个链表-- 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));
		}
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值