Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit3e5e264

Browse files
add leetcode 143
1 parentc6369b7 commit3e5e264

File tree

2 files changed

+68
-10
lines changed

2 files changed

+68
-10
lines changed

‎.idea/workspace.xml

Lines changed: 11 additions & 10 deletions
Some generated files are not rendered by default. Learn more aboutcustomizing how changed files appear on GitHub.

‎leetcode/143. Reorder List.py

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
'''
2+
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
3+
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
4+
5+
You must do this in-place without altering the nodes' values.
6+
7+
For example,
8+
Given {1,2,3,4}, reorder it to {1,4,2,3}.
9+
'''
10+
11+
12+
# Definition for singly-linked list.
13+
classListNode(object):
14+
def__init__(self,x):
15+
self.val=x
16+
self.next=None
17+
18+
classSolution(object):
19+
defreorderList(self,head):
20+
ifnotheadornothead.next:
21+
return
22+
ahead,behind=self.split(head)
23+
behind=self.reverse(behind)
24+
head=self.reConnect(ahead,behind)
25+
# split the linkedlist in middle
26+
defsplit(self,head):
27+
fast=head
28+
slow=head
29+
whilefastandfast.next:
30+
slow=slow.next
31+
fast=fast.next
32+
fast=fast.next
33+
middle=slow.next
34+
slow.next=None
35+
returnhead,middle
36+
# reverse the behind half linkedlist
37+
defreverse(self,head):
38+
reHead=None
39+
curNode=head
40+
whilecurNode:
41+
nextNode=curNode.next
42+
curNode.next=reHead
43+
reHead=curNode
44+
curNode=nextNode
45+
returnreHead
46+
# merge the two linkedlist to one
47+
defreConnect(self,first,second):
48+
head=first
49+
tail=first
50+
first=first.next
51+
whilesecond:
52+
tail.next=second
53+
tail=tail.next
54+
second=second.next
55+
iffirst:
56+
first,second=second,first
57+
returnhead

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp