1.字符串反转
字符串反转有很多种方式,举例其中常见的3种
a = "hello"
a_reverse= a[::-1]
print(a_reverse)
b = "yangyangchi"
b_list = list(b)
b_list.reverse()
b_reverse = ''.join(b_list)
print(b_reverse)
def reverse(c):
c_reverse =""
for i in range(1,len(c)+1):
c_reverse+= c[len(c) - i]
return c_reverse
print(reverse("qwert"))
2.循环反转单链表
循环的方法中,使用pre指向前一个结点,cur指向当前结点,每次把cur->next指向pre即可
#coding="utf-8"
class ListNode:
def __init__(self, x):
self.val = x;
self.next = None;
def nonrecurse(head):
if head is None or head.next is None:
return head;
pre = None;
cur = head;
h = head;
while cur:
h = cur;
tmp = cur.next;
cur.next = pre;
pre = cur;
cur = tmp;
return h;
head = ListNode(1);
p1 = ListNode(2);
p2 = ListNode(3);
p3 = ListNode(4);
head.next = p1;
p1.next = p2;
p2.next = p3;
p = nonrecurse(head);
while p:
print p.val;
p = p.next;