牛客[編程題] HJ48 從單向鏈表中刪除指定值的節(jié)點
中等 通過率:42.97% 時間限制:1秒 空間限制:32M
描述
輸入一個單向鏈表和一個節(jié)點的值,從單向鏈表中刪除等于該值的節(jié)點,刪除后如果鏈表中無節(jié)點則返回空指針。
鏈表的值不能重復。
構造過程,例如輸入一行數(shù)據(jù)為:
6 2 1 2 3 2 5 1 4 5 7 2 2
則第一個參數(shù)6表示輸入總共6個節(jié)點,第二個參數(shù)2表示頭節(jié)點值為2,剩下的2個一組表示第2個節(jié)點值后面插入第1個節(jié)點值,為以下表示:
1 2 表示為
2->1
鏈表為2->1
3 2表示為
2->3
鏈表為2->3->1
5 1表示為
1->5
鏈表為2->3->1->5
4 5表示為
5->4
鏈表為2->3->1->5->4
7 2表示為
2->7
鏈表為2->7->3->1->5->4
最后的鏈表的順序為 2 7 3 1 5 4
最后一個參數(shù)為2,表示要刪掉節(jié)點為2的值
刪除 結點 2
則結果為 7 3 1 5 4
數(shù)據(jù)范圍:鏈表長度滿足 1 \le n \le 1000 \ ,節(jié)點中的值滿足 0 \le val \le 10000 \
測試用例保證輸入合法
輸入描述:
輸入一行,有以下4個部分:
1 輸入鏈表結點個數(shù)
2 輸入頭結點的值
3 按照格式插入各個結點
4 輸入要刪除的結點的值
輸出描述:
輸出一行
輸出刪除結點后的序列,每個數(shù)后都要加空格
示例1
輸入:
5 2 3 2 4 3 5 2 1 4 3
輸出:
2 5 4 1
說明:
形成的鏈表為2->5->3->4->1
刪掉節(jié)點3,返回的就是2->5->4->1
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
string line;
while ((line = System.Console.ReadLine()) != null)
{ // 注意 while 處理多個 case
var arr = line.Split(" ");
int len = int.Parse(arr[0]);
int head = int.Parse(arr[1]);
int remove = int.Parse(arr[arr.Length-1]);
List<int> list = new List<int>();
list.Add(head);
int cur, before;
for (int i = 2; i < 2*len; i+=2)
{
cur = int.Parse(arr[i]);
before = int.Parse(arr[i + 1]);
for (int j = 0; j < list.Count; j++)
{
if (before==list[j])
{
list.Insert(j+1,cur);
}
}
}
list.Remove(remove);
string res = string.Empty;
for (int i = 0; i < list.Count; i++)
{
res += list[i].ToString();
if (i!= list.Count-1)
{
res += " ";
}
}
Console.WriteLine(res);
}
}
}
浙公網(wǎng)安備 33010602011771號