//scala
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
object Solution {
def removeNthFromEnd(head: ListNode, n: Int): ListNode = {
var first = head
var second = head
if(first==null)
return head.next
for(i <- 1 to n)
first = first.next
while(first.next!=null){
first = first.next
second = second.next
}
second.next = second.next.next
head
}
}
//python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
first = head
second = head
while n > 0:
first = first.next
n -= 1
if first==None:
return head.next
while first.next:
first = first.next
second = second.next
second.next = second.next.next
return head
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: ListNode) -> ListNode:
pos = 0
first = head
second = head
if first == None or first.next == None:
return None
while first!=None and first.next!=None and first.next.next!=None:
first = first.next.next
second = second.next
#判断是否有环
if first == second:
pos += 1
#有环的话,计算出环的大小
while first.next != second:
first = first.next
pos += 1
break
if pos == 0:
return None
else:
first = head
second = head
#找出环的位置
while pos > 0:
first = first.next
pos -= 1
while first != second:
first = first.next
second = second.next
return second
找出链表的中间节点 解题思路: 快引用和慢引用
/**
* Definition for singly-linked list.
* class ListNode(var _x: Int = 0) {
* var next: ListNode = null
* var x: Int = _x
* }
*/
object Solution {
def middleNode(head: ListNode): ListNode = {
var fast = head
var low = head
while(fast!=null && fast.next!=null){
low = low.next
fast = fast.next.next
}
low
}
}