问题重述
Problem Statement:
You are given the head of a linked list and two integers, i
and j
. You have to retain the first i
nodes and then delete the next j
nodes. Continue doing so until the end of the linked list.
Example: * linked-list = 1 2 3 4 5 6 7 8 9 10 11 12
* i = 2
* j = 3
* Output = 1 2 6 7 11 12
python实现
1 | # LinkedList Node class for your reference |
测试用例: 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# helper functions for testing purpose
def create_linked_list(arr):
if len(arr)==0:
return None
head = Node(arr[0])
tail = head
for data in arr[1:]:
tail.next = Node(data)
tail = tail.next
return head
def print_linked_list(head):
while head:
print(head.data, end=' ')
head = head.next
print()
def test_function(test_case):
head = test_case[0]
i = test_case[1]
j = test_case[2]
solution = test_case[3]
temp = skip_i_delete_j(head, i, j)
index = 0
try:
while temp is not None:
if temp.data != solution[index]:
print("Fail")
return
index += 1
temp = temp.next
print("Pass")
except Exception as e:
print("Fail")
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
i = 2
j = 2
head = create_linked_list(arr)
solution = [1, 2, 5, 6, 9, 10]
test_case = [head, i, j, solution]
test_function(test_case)
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
i = 2
j = 3
head = create_linked_list(arr)
solution = [1, 2, 6, 7, 11, 12]
test_case = [head, i, j, solution]
test_function(test_case)
arr = [1, 2, 3, 4, 5]
i = 2
j = 4
head = create_linked_list(arr)
solution = [1, 2]
test_case = [head, i, j, solution]
test_function(test_case)