#encoding=utf-8
class ListNode:
def __init__(self,x):
self.val=x;
self.next=None;
#链表逆序
def reverse(head): #循环的方法反转链表
if head is None or head.next is None:
return head;
pre=None;
cur=head;
head2=0
while cur:
head2=cur;
tmp=cur.next;
cur.next=pre;
pre=cur;
cur=tmp;
return head2
#链表长度
def length(head):
pre = head
length = 0
while pre:
length += 1
pre = pre.next
return length
#追加节点
def add(head,data):
node=ListNode(data)
pre=head
while pre.next:
pre=pre.next
pre.next=node
#清空链表
def clear(head):
head.val=None
head.next=None
#获取节点
def get(head,index):
pre=head
index-=1
while index:
pre=pre.next
index-=1
return pre
#设置节点
def set(head,index,data):
n=get(head,index)
n.val=data
return n
#插入节点
def insert(head,index,data):
node=ListNode(data)
n=get(head,index-1)
node.next=n.next
n.next=node
#遍历链表
def show(head):
p=head
while p:
print p.val;
p=p.next;
#删除节点
def delete(head,index):
n=get(head,index-1)
n.next=n.next.next
head=ListNode(1); #测试代码
p1=ListNode(2); #建立链表1->2->3->4->None;
p2=ListNode(3);
p3=ListNode(4);
head.next=p1;
p1.next=p2;
p2.next=p3;
p=reverse(head); #输出链表 4->3->2->1->None
print '逆序:'
show(p)
clear(head)
print head.val,head.next
head=ListNode(1); #测试代码
p1=ListNode(2); #建立链表1->2->3->4->None;
p2=ListNode(3);
p3=ListNode(4);
head.next=p1;
p1.next=p2;
p2.next=p3;
print 'len:',length(head)#len: 4
add(head,5)
print 'len:',length(head)#len: 5
print get(head,3).val#3
print set(head,3,13).val#13
insert(head,3,12)
print'插入后:'
show(head)
print'删除后:'
delete(head,3)
show(head)