1. 字符串逆序,abcde->edcba
2. 单词逆序,how are you->you are how
3. 单链表逆序,[1,2,3,4,5]->[5,4,3,2,1]
a = 'abcde'
print '原始字符串:', a
print '翻转字符串:',a[::-1]
def reverse(arr, left, right):
"""
字符串反转
定义两个索引分别指向首位,交换2个索引的位置,
同时把索引的值向中间移动,直到两个索引相遇为止
"""
while(left < right):
arr[left],arr[right] = arr[right],arr[left]
left += 1
right -= 1
return ''.join(arr)
print '翻转字符串:', reverse(list(a), 0, len(a)-1)
def str_reverse():
"""
把一个句子中的单词进行反转"how are you"-->"you are how"
思路:
1. 先对字符串进行反转->"uoy era woh"
2. 遍历字符串,遇到空格,对单个单词进行反转
"""
word_str = 'how are you'
lists = list(word_str)
word_str_r = reverse(lists, 0, len(word_str)-1)
print 'lists: ', lists
i, begin = 0, 0
while i < len(lists):
if lists[i] == ' ':
print 'begin: ', begin, 'i: ',i, 'tmp: ', lists
reverse(lists, begin, i-1)
begin = i + 1
i += 1
reverse(lists, begin, len(lists)-1)
return ''.join(lists)
print str_reverse()
class LNode():
#__new__ 负责对象的创建而 __init__ 负责对象的初始化
def __new__(self, data):
self.data = data
self.next = None
def list_reverse(phead):
"""
链表反转
...h-->i-->j-->k-->... <图1>
...h<--i j-->... <图2>
假如h节点之前的指针已经调整完毕,下面将i的next指向h(图2)
为了避免i与j断开,在调整节点i的next之前,先把节点j保存下来
在调整节点i的next指针时,i指向h,所以还需要知道i的前一个节点h
此处定义3个指针,分别是当前遍历到的节点pnode,它的前一个节点pprev及后一个节点pnext
"""
preverse_head = None
pnode = phead
pprev = None
while(pnode != None):
pnext = pnode.next
if pnext == None:
preverse_head = pnode
pnode.next = pprev
pprev = pnode
pnode = pnext
return preverse_head
a = [1,2,3,4,5]
def list_create(a):
"""
构造单链表
"""
head = LNode()
head.next = None
cur = head
for i in a:
tmp = LNode()
tmp.data = i
tmp.next = None
cur.next = tmp
cur = tmp
return head
def test():
head = list_create(a)
print '排序前:'
cur = head.next
while cur != None:
print cur.data
cur = cur.next
preverse_head = list_reverse(head.next)
print '排序后:'
cur = preverse_head
while cur != None:
print cur.data
cur = cur.next
test()
运行结果: