奇偶連結串列的 Python 實現
假設我們有一個單鏈表,我們必須將所有奇數節點分組,然後是偶數節點。我們所說的節點位置而不是節點中的值。我們應該嘗試就地處理。因此,如果節點為 [1,22,13,14,25],則結果將為 [1,13,25,22,14]
要解決此問題,我們將按照以下步驟操作:
- 如果 head 為 null 或 head 的下一個節點為 null,則返回 head
- head1 := head,head2 := head 的下一個節點,head_beg := head 的下一個節點
- 如果 head2 的下一個節點不為 null 並且 (head 的下一個節點的下一個節點不為 null)
- head1 的下一個節點 := head2 的下一個節點
- head2 的下一個節點 = (head 的下一個節點的下一個節點)
- head1 := head1 的下一個節點,head2 := head2 的下一個節點
- 如果 head2 的下一個節點不為 null
- head1 的下一個節點 := head2 的下一個節點
- head1 := head1 的下一個節點
- head1 的下一個節點 := head2_beg,head2 的下一個節點 = null
- 返回 head
讓我們看看以下實現以進行更好的理解:
示例
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution(object):
def oddEvenList(self, head):
if head == None or head.next ==None:
return head
head1=head
head2,head2_beg= head.next,head.next
while head2.next!= None and head2.next.next!= None:
head1.next = head2.next
head2.next = head2.next.next
head1 = head1.next
head2 = head2.next
if head2.next!=None:
head1.next = head2.next
head1 = head1.next
head1.next = head2_beg
head2.next = None
return head
ob1 = Solution()
head = make_list([1,22,13,14,25])
print_list(ob1.oddEvenList(head))輸入
[1,22,13,14,25]
輸出
[1, 13, 25, 22, 14, ]
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP