训练营day3-4-5:leetcode 203、leetcode 206、

今天是链表,好烦啊,主要是烦链表的创建,划水篇

1、203. 移除链表元素

没啥好说的,最基本的操作,注意创建空的头结点

def removeElements203(head, val):
    newhead = ListNode()
    newhead.next = head
    cur = head
    head = newhead
    while (cur):
        if (cur.val != val):
            head.next = cur
            head = head.next
        cur = cur.next
    head.next = None
    return newhead.next

 完整版,创建,显示

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next
def printh(head):
    data = []
    while(head):
        data.append(head.val)
        head = head.next
    print(data)

def removeElements203(head, val):
    newhead = ListNode()
    newhead.next = head
    cur = head
    head = newhead
    while (cur):
        if (cur.val != val):
            head.next = cur
            head = head.next
        cur = cur.next
    head.next = None
    return newhead.next

head = [1,2,6,3,4,5,6]
val = 6
b =  ListNode()
h = b
for i in range(len(head)):
    a = ListNode()
    a.val = head[i]
    a.next= None
    b.next = a
    b = b.next
h = h.next
printh(h)
n = removeElements203(h, val)
printh(n)

 2、206. 反转链表

比较简单,没啥好说的

def reverseList206(head):
    newhead = None

    while(head):
        nxt = head.next
        head.next = newhead
        newhead = head
        head = nxt
        #printh(newhead)

    return newhead

3、24. 两两交换链表中的节点

def swapPairs24(head):
    newhead = ListNode()
    pre = newhead
    cur = head

    while(cur ):
        nxt = cur.next
        if nxt is None:
            break
        print(pre.val,cur.val,nxt.val)
        pre.next = nxt
        tm = nxt.next
        nxt.next = cur
        pre = cur
        cur = tm
        #nxt = cur.next
    pre.next = cur
    #print(pre.val, cur.val, nxt.val)
    return newhead.next

4、面试题 02.07. 链表相交

这道竟然是简单,,,

好复杂,双指针还是有点想法的,简单版本都没做出来,不想记录了,累了,链表真是不爱做,就这吧,

你可能感兴趣的:(代码随想录训练营,leetcode,链表,python)