问题重述

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# LinkedList Node class for your reference
class Node:
def __init__(self, data):
self.data = data
self.next = None

def skip_i_delete_j(head, i, j):
node = head
counter = 1
flag = True
while node != None:
if flag and counter == i:
flag = False
pre_node = node
counter = 0
if not flag and counter == j:
flag = True
pre_node.next = node.next
counter = 0
elif not flag and node.next is None:
pre_node.next = node.next
node = node.next
counter += 1
return head

测试用例:

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)