def ReverseList(pHead): # write code here # write code here if not pHead or not pHead.next: return pHead last = None while pHead: tmp = pHead.next pHead.next = last last = pHead pHead = tmp return last
题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
def deleteDuplication(head): if head is None: return None node=ListNode(0) node.next=head p=node cur=head while cur: if cur.next and cur.next.val==cur.val: tmp=cur.next while tmp and tmp.val==cur.val: tmp=tmp.next p.next=tmp cur=tmp else: p=cur cur=cur.next return node.next
题目描述:链表相邻节点进行翻转,不能直接拷贝值
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
def swapPairs(self, head): if not head or not head.next: return head p1=newHead=ListNode(-1) newHead.next=head while p1 and p1.next and p1.next.next: p0,p1,p2=p1,p1.next,p1.next.next p0.next,p1.next,p2.next=p2,p2.next,p1 return newHead.next