Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
這個題的思路就是用兩個指針p和q指向head,然後q向後移動n步,進入循環,p和q同時向後移動,直到q.next爲空,去掉p後面的節點。還有就是對於q爲空,q.next不存在進行特殊討論下。
leetcode提交代碼
class Solution():
def removeNthFromEnd(self, head, n):
p=head
q=head
while n!=0:
q=q.next
n=n-1
if q==None :
return head.next
while q.next!=None:
p=p.next
q=q.next
r=p.next
p.next=r.next
return head
另外附上可以檢驗的代碼
# -*- coding: utf-8 -*
class Node(object):
def __init__(self,val,p=None):
self.data = val
self.next = p
class list(object):
def __init__(self): #頭節點爲0
self.head = 0
def initlist(self,data):
self.head = Node(data[0])
p = self.head
for i in data[1:]:
node = Node(i)
p.next = node
p = p.next
class Solution():
def removeNthFromEnd(self, head, n):
p=head
q=head
while n!=0:
q=q.next
n=n-1
if q==None :
return head.next
while q.next!=None:
p=p.next
q=q.next
r=p.next
p.next=r.next
return head
def shuchu(self,head):
p=head
while p!=None:
print p.data
p=p.next
s = Solution()
l=list()
l.initlist([1,2,3,4])
p=s.removeNthFromEnd(l.head,3)
s.shuchu(p)