1、从头到尾打印链表
输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。
# -*- coding:utf-8 -*-class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: def printListFromTailToHead(self, listNode): l =[] while listNode: l.append(listNode.val) listNode = listNode.next return l[::-1]
2、链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个结点。
# -*- coding:utf-8 -*-class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: def FindKthToTail(self, head, k): node_list = [] while head: node_list.append(head) head = head.next if k < 1 or k > len(node_list): return return node_list[-k]
3、反转链表
输入一个链表,反转链表后,输出新链表的表头。
# -*- coding:utf-8 -*-class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def ReverseList(self, pHead): if pHead is None or pHead.next is None: return pHead pre = None cur = pHead while cur: temp = cur.next cur.next = pre pre = cur cur = temp return pre
待续...