defcreateList(value_list: list) -> ListNode: """Create Linked List based on list :param value_list: list :return: NodeList """ _len = len(value_list) if _len == 0: returnNone if _len == 1: return ListNode(value_list[0]) else: root = ListNode(value_list[0]) tmp = root for i inrange(1, _len): # 声明当前节点,再把当前节点与前面节点联系在一起。 tmp.next = ListNode(value_list[i]) tmp = tmp.next# 更新tmp return root # 返回根节点
逐个输出链表节点
1 2 3 4 5 6 7 8 9 10
defprintList(head: ListNode): """Print single node one by one in linked list :param head: ListNode :return: None """ p = head while p != None: # print() print(p) # 由于有ListNode实现了__str__函数 就不用调用p.val来获取节点值了 p = p.next
获取链表长度
7行代码获取链表长度 written by hand require
1 2 3 4 5 6 7 8 9 10 11
deflistLength(head: ListNode) -> int:# 7 """Get the length of linked list :param head: ListNode :return: int """ count = 0# 1 p = head # 2 while p != None: # 3 count += 1# 4 p = p.next# 5 return count # 6
插入ListNode
12行代码实现链表节点插入(注意 while local != 1: 的条件) written by hand require
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
definsertList_V1(head: ListNode, local: int, val: int) -> ListNode:# 1 """Insert ListNode :param head: ListNode :param local: int :param val: int :return: ListNode """ if local < 0or local > listLength(head): return# 2 dummy = ListNode(None) # 3 dummy.next = head # 4 p = dummy # 5 while local != 1: # 6 p = p.next# 7 local -= 1# 8 tmp_node = ListNode(val) # 9 tmp_node.next = p.next# 10 p.next = tmp_node # 11
definsertList(head: ListNode, local: int) -> ListNode: """Instert ListNode into certain current linked list :param head: ListNode :param local: int (index start from 1) :return: ListNode """ if local < 0or local > listLength(head): return head insert_value = input("Enter a val: ") if local == 1: # 插到第一个位置 其他节点自动后移 tmp_Node = ListNode(insert_value) tmp_Node.next = head return tmp_Node # 否则插入位置大于1 p = head # 循环n次达到n+1 所以这里是local != 2 而不是local != 1 插入的位置,实际上是要找到插入位置的前序位置。 while local != 2: p = p.next local -= 1 tmp_Node = ListNode(insert_value) tmp_Node.next = p.next p.next = tmp_Node
return head
删除ListNode
10行代码实现删除链表节点(注意这个删除操作的写法 p.next = p.next.next) written by hand require
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
defdeleteListNode(head: ListNode, local: int) -> ListNode:# 1 """Remove the certain ListNode in the linked list :param head: ListNode :param local: int :return ListNode: """ if local < 0or local > listLength(head): return head # 2 dummy = ListNode(None) # 3 dummy.next = head # 4 p = dummy # 5 while local != 1: # 6 p = p.next# 7 local -= 1# 8 p.next = p.next.next# 9
return dummy.next# 10
一个不使用哑节点的版本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
defdeleteList(head: ListNode, local: int) -> ListNode: """Remove the certain ListNode in the linked list :param head: ListNode :param local: int :return ListNode: """ if local < 1or local > listLength(head): # 待删除节点不在链表中 直接返回 return head elif local == 1: head = head.next else: p = head while local != 2: p = p.next local -= 1 tmp_p = p.next p.next = tmp_p.next return head
链表反转
递归 6行 代码
1 2 3 4 5 6 7 8 9 10
defreverseList(head: ListNode) -> ListNode:# 1 """reverse Linked List :param head: ListNonde :return: ListNonde """ if head == Noneor head.next == None: return head # 2 p = reverseList(head.next) # 3 head.next.next = head # 4 head.next = None# 5 return p # 6
循环 13行 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defreverseList(self, head: ListNode) -> ListNode:# 1 """reverse Linked List :param head: ListNonde :return: ListNonde """ if head == Noneor head.next == None: return head # 2 dummy = ListNode(None) # 3 dummy.next = head # 4 pre_p = dummy # 5 p = head # 6 while p: # 7 next_p = p.next# 8 p.next = pre_p # 9 pre_p = p # 10 p = next_p # 11 # 完成反转之后要把head.next设置为None。防止循环链表出现。 head.next = None# 12 return pre_p # 13
LinkedList 转Python List
1 2 3 4 5 6 7 8 9 10 11
defconvert2list(head: ListNode) -> list: """Convert linked list to normal list :param head: ListNonde :return: list """ res = [] p = head while p != None: res.append(p.val) # 由于有ListNode实现了__str__函数 就不用调用p.val来获取节点值了 p = p.next return res
defmain(): value_list = [1, 2, 3, 4, 5] print("Create a Linklist: ") head = createList(value_list) print("Length of LinkedListed: {}".format(listLength(head))) printList(head) print("-"*50)
n1 = input("Enter the index to insert(start form 1): ") n1 = int(n1) insert_val = input("Enter a val: ") head = insertList_V1(head, n1, insert_val) print("Length of LinkedList: {}".format(listLength(head))) printList(head) print("-"*50)
n2 = input("Enter the index to delete(start form 1): ") n2 = int(n2) head = deleteList(head, n2) print("Length of LinkedList: {}".format(listLength(head))) printList(head)
voidLinkedList::Search(int val){ ListNode* p = head; if(p==NULL){ cout << "There is no postition in this List!" << endl; return; } int counter = 0; while(p != NULL && p->val != val){ p = p->next; counter++; } cout << "the value you want to search is at position " << counter << endl; }
获取特定节点上的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
intLinkedList::getValueAt(int position){ ListNode* p = head; if(p == NULL){ std::cout << "It is an empty Linked List!" << endl; }else{ int posi = 0; while (p!= NULL && posi != position){ posi++; p = p->next; } if (p == NULL){ cout << "There is no value of this postition in this List!" << endl; }else{ cout << "In this Position, the vuale is " << p->val << endl; } } return p->val; }
设置特定节点上的值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
voidLinkedList::setValueAt(int position, int val){ ListNode* p = head; if(p == NULL){ cout << "It is an empty Linked List!" << endl; }else{ int posi = 0; while (p!= NULL && posi != position){ posi++; p = p->next; } if (p == NULL){ cout << "There is no value of this postition in this List!" << endl; }else{ p->val = val; cout << "The Value in this position has been Updated!" << endl; } } }
*************************** 创建链表开始 输出Linked List创建结果 1 2 3 4 5 6 7 8 *************************** 获取链表长度为 8 *************************** 插入Linked List!100 输出Linked List插入结果 1 2 3 4 5 6 7 8 100 *************************** 删除Linked List 7! The Deletion Operation had been finished! 输出Linked List删除结果 1 2 3 4 5 6 8 100 *************************** 输出Linked List反转结果 100 8 6 5 4 3 2 1 *************************** 在LinkedList中搜索值为6的节点的位置 the value you want to search is at position 2 *************************** 设置LinkedList第3位节点的数值为50 The Value in this position has been Updated! 100 8 6 50 4 3 2 1 *************************** 获得LinkedList第2位节点的数值 In this Position, the vuale is 6
while l1 or l2: x= l1.val if l1 else0 y= l2.val if l2 else0 s = carry + x + y carry = s//10# 计算进位 r.next = ListNode(s%10) # 计算余数 r = r.next if l1 != None: l1 = l1.next if l2 != None: l2 = l2.next # 最后还做了个特判 if carry > 0: r.next=ListNode(1)
for i inrange(1, n+1): first = first.next while first.next != None: first = first.next second = second.next second.next = second.next.next return dummy.next
# 将head之后的k个node(包括head本身)入栈 while count and tmp: stack.append(tmp) tmp = tmp.next count -= 1
while stack: p.next = stack.pop() p = p.next
指针(建议看题解理解过程)
1 2 3 4
cur = pre.next# 获取下一个元素 第一个获取的是head.next pre.next = cur.next# pre与cur.next连接起来,此时cur(孤单)掉了出来 cur.next = tail.next# 和剩余的链表连接起来 tail.next = cur # 插在tail后面
递归
1 2 3 4 5 6 7 8 9 10 11
if count == k: # 将下一层递归翻转后的head节点作为cur cur = self.reverseKGroup(cur, k) while count: tmp = head.next head.next = cur cur = head head = tmp count -= 1 head = cur return head # head逐渐后移最终会指向tail
i = nums_len - 2 while i >= 0and nums[i+1] <= nums[i]: # 从后往前找 找一个后面大于前面数字的位置 i i -= 1 if i >= 0: j = nums_len - 1 while j >=0and nums[j] <= nums[i]: # 从后往前找 找一个比nums[i]要小的位置 j -= 1 self.swape(nums, i, j) # 交换nums[i]和nums[j] self.reverse(nums, i + 1)
使用 p 指针进行遍历,small 指针跟踪保存较小的那一部分,big 指针跟踪保存较大的那一部分。 一次遍历结束之后,将 small 和 big 拼接返回即可,注意,由于可能出现数字0,所以判断 small 或 big 部分非空的条件不是 if samll.val 而是 small.val != None。
关键代码
1 2 3 4 5 6 7 8
while p: if p.val < x: small.next = p small = small.next else: big.next = p big = big.next p = p.next
nodesSeen = list() while head: # 这里不能用Value(head.val)做判断,而要用ListNode(head)做判断。 if head in nodesSeen: returnTrue else: nodesSeen.append(head) head = head.next returnFalse
快慢指针
1 2 3 4 5
while slow != fast: if fast == Noneor fast.next == None: # 这一点很关键 returnFalse slow = slow.next fast = fast.next.next