Skip to content

Commit 8b145ce

Browse files
committed
New Simple Approachable LinkedList Solution
1 parent aca3f80 commit 8b145ce

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

Bit-Manipulation/Power-of-2.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
def isPowerofTwo(n):
2+
return n and (not(n and (n-1)))
3+
print isPowerofTwo(9)

Bit-Manipulation/Xor-upto-n.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
def xorUptoN(n):
2+
if n%4 == 0:
3+
return n
4+
if n%4 == 1:
5+
return 1
6+
if n%4 == 2:
7+
return n + 1
8+
else:
9+
return 0
10+
11+
print xorUptoN(6)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
'''
2+
Given a linked list, swap every two adjacent nodes and return its head.
3+
4+
For example,
5+
Given 1->2->3->4, you should return the list as 2->1->4->3.
6+
7+
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
8+
'''
9+
#Approach 1
10+
def swapPairs(self, head):
11+
pre, pre.next = self, head
12+
while pre.next and pre.next.next:
13+
a = pre.next
14+
b = a.next
15+
pre.next, b.next, a.next = b, a, b.next
16+
pre = a
17+
return self.next
18+
19+
20+
#Approach 2
21+
def swapPairs(head):
22+
curr = head
23+
nxt = head.next
24+
while curr and nxt:
25+
curr.val, nxt.val = nxt.val, curr.val
26+
curr = nxt.next
27+
if curr:
28+
nxt = curr.next
29+
return head

0 commit comments

Comments
 (0)