Pointer speed penultimate node K, each group of K inverted list

A node in the linked list to find the way, from the node to the tail pointer is K

A node in the linked list to find the way, from the node to the tail pointer is K. 0 penultimate node list tail pointer of the linked list. Required time complexity is O (n).
LLI node is defined as follows:
struct ListNode
{
int m_nKey;
ListNode * m_pNext;
}
initializes the value of the node list 1,2,3,4,5,6,7.

Enter a description:
该节点到尾指针的距离K
Output Description:
返回该单向链表的倒数第K个节点,输出节点的值

Example 1

Entry
2
Export
6

In fact, it is to find the penultimate K nodes thing.

链接:https://www.nowcoder.com/questionTerminal/0cff324157a24a7a8de3da7934458e34?f=discussion
class Node:
    def __init__(self,x):
        self.val = x
        self.next = None
head = Node(0)
temp = head
for i in range(1,8):
    node = Node(i)
    temp.next = node
    temp = node
 
first = head.next
i = 0
k = int(input())
while i < k-1:
    first = first.next
    i += 1
slow = head.next
while first.next:
    first = first.next
    slow = slow.next
print(slow.val)

Each of K group reverse list

The answer from A primary

Enter a description:
第一行输入是链表的值第二行输入是K的值,K是大于或等于1的整数输入形式为:1 2 3 4 52
Output Description:
当 k = 2 时,应当输出:2 1 4 3 5当 k = 3 时,应当输出:3 2 1 4 5当k=6时,应当输出:1 2 3 4 5
Entry
1 2 3 4 5
2
Export
2 1 4 3 5
确定k有几组,然后用reverse循环翻转每组,
reverse翻转cishu = k//2次,举例3,4时,翻转1,2次,很合理。
链接:https://www.nowcoder.com/questionTerminal/a632ec91a4524773b8af8694a51109e7?f=discussion
#必须3才可以过

def reverse(array, left, right, k):
    cishu = k // 2
    while cishu > 0:
        array[left], array[right] = array[right], array[left]
        left += 1
        right -= 1
        cishu -= 1
 
array = list(map(int, input().split()))
k = int(input())
beishu = len(array) // k
left = 0
right = k-1
for i in range(beishu):
    reverse(array, left, right, k)
    left += k
    right += k
 
print(" ".join(str(i) for i in array))

Guess you like

Origin www.cnblogs.com/qizhien/p/11607235.html
Recommended