-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Reversed 2 linked list. Today we shared the song OldStreet. Time is r…
…eally slow on the old street.
- Loading branch information
Meng Wei
authored and
Meng Wei
committed
Jan 11, 2018
1 parent
074bbaf
commit 714a4cb
Showing
2 changed files
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
# Definition for singly-linked list. | ||
# class ListNode(object): | ||
# def __init__(self, x): | ||
# self.val = x | ||
# self.next = None | ||
|
||
# EASY | ||
# Iteratively: T:O(N) S:O(1) | ||
# Recursively: T:O(N) S:O(N) | ||
class Solution(object): | ||
def reverseList(self, head): | ||
""" | ||
:type head: ListNode | ||
:rtype: ListNode | ||
""" | ||
# Iteratively | ||
# rev = None | ||
# while head!=None: | ||
# temp = head.next | ||
# head.next = rev | ||
# rev = head | ||
# head = temp | ||
# return rev | ||
|
||
# Recursively | ||
return self._reverse(head,None) | ||
|
||
def _reverse(self,head,prev): | ||
if head == None: | ||
return prev | ||
else: | ||
temp = head.next | ||
head.next = prev | ||
return self._reverse(temp,head) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
# Medium | ||
# O(N) O(1) | ||
|
||
|
||
# Definition for singly-linked list. | ||
# class ListNode(object): | ||
# def __init__(self, x): | ||
# self.val = x | ||
# self.next = None | ||
|
||
class Solution(object): | ||
def reverseBetween(self, head, m, n): | ||
""" | ||
:type head: ListNode | ||
:type m: int | ||
:type n: int | ||
:rtype: ListNode | ||
""" | ||
i = 0 | ||
if(m==n): | ||
return head | ||
dummy = ListNode(0) | ||
dummy.next = head | ||
ret = dummy | ||
while dummy: | ||
if i+1==m: | ||
dummy.next = self.reverseBegin(dummy.next, n-i) | ||
return ret.next | ||
i += 1 | ||
dummy = dummy.next | ||
|
||
def reverseBegin(self, node, k): | ||
i = 0 | ||
rev = None | ||
ret = node | ||
while i<k: | ||
i += 1 | ||
temp = node.next | ||
node.next= rev | ||
rev = node | ||
node = temp | ||
ret.next = temp | ||
return rev | ||
|