题目
https://leetcode.com/problems/design-linked-list/
解题
- 分情况讨论的思维(if-else),要养成习惯
- 如何去设计/定义一个class,以及class里面的变量和方法
class MyLinkedList(object):
class Node(object):
def __init__(self, x, nextNode):
self.val = x
self.next = nextNode
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = None
self.count = 0
def get(self, index):
"""
Get the value of the index-th node in the linked list. If the index is invalid, return -1.
:type index: int
:rtype: int
"""
p = self.head
if self.count == 0 or index > self.count - 1:
return -1
i = 0
while i < index:
p = p.next
i += 1
return p.val
def addAtHead(self, val):
"""
Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
:type val: int
:rtype: None
"""
node = self.Node(val, self.head)
self.head = node
self.count += 1
def addAtTail(self, val):
"""
Append a node of value val to the last element of the linked list.
:type val: int
:rtype: None
"""
node = self.Node(val, None)
if self.count == 0:
self.head = node
else:
p = self.head
i = 0
while i < self.count -1:
p = p.next
i += 1
p.next = node
self.count += 1
def addAtIndex(self, index, val):
"""
Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted.
:type index: int
:type val: int
:rtype: None
"""
p = self.head
if index == self.count:
self.addAtTail(val)
elif index > self.count:
return
else:
i = 0
while i < index - 1:
p = p.next
i += 1
node = self.Node(val, p.next)
p.next = node
self.count += 1
def deleteAtIndex(self, index):
"""
Delete the index-th node in the linked list, if the index is valid.
:type index: int
:rtype: None
"""
p = self.head
if index >= self.count:
return
else:
i = 0
while i < index - 1:
p = p.next
i += 1
p.next = p.next.next
self.count -= 1