image.png
官方
image.png
1.定義鏈表節(jié)點(diǎn)
2.定義:題目給的鏈表
3.制作一個(gè)函數(shù):能展示鏈表的結(jié)果:能遍歷鏈表展示結(jié)果
4.真正運(yùn)行的函數(shù)中:
制作兩個(gè)鏈表 一個(gè)是奇數(shù)鏈表,一個(gè)是偶數(shù)鏈表,最后將奇數(shù)鏈表拼接在偶數(shù)鏈表之前
錯(cuò)誤記錄:
1.在oddEvenList循環(huán)里i每輪循環(huán)需要疊加1
2.比如輸入是12345,需要先做兩個(gè)鏈表检盼,奇鏈表:[1,3,5] 偶鏈表:[2,4]
然后將5的next指向2亭枷,但是這里有個(gè)坑就是4還是在原來的情況下指向5的河爹!需要將4指向None植捎,因?yàn)榕兼湵砜隙ㄊ瞧唇釉谧詈蟮?br>
3.邊界情況沒有處理贩挣,比如輸入是[1,2]或[1]只有兩位或是只有一位就不需要置換了
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def oddEvenList(head: ListNode) -> ListNode:
if not head or not head.next:
return head
return_head = head
first_second = head.next
first, second = head, head.next
head = second.next
i = 1
while head:
if i % 2 == 1:
first.next = head
first = head
else:
second.next = head
second = head
head = head.next
i += 1 #忘記疊加了/尾巴沒有處理/邊界情況沒有處理
second.next = None
first.next = first_second
return return_head
def get_ListNode():
p = ListNode(val=5, next=None)
for i in [4, 3, 2, 1]:
p = ListNode(val=i, next=p)
return p
def traverse(head):
print(head.val)
while head.next:
head = head.next
print(head.val)
res_head = oddEvenList(get_ListNode())
traverse(res_head)