两两交换链表中的节点
我的思路:
def swapPairs(self, head):
if not head or not head.next:
return head
prehead=ListNode(-1)
prehead.next=head
cur,pre=head,prehead
while cur and cur.next:
next=cur.next
cur.next=next.next
next.next=cur
pre.next=next
pre=cur
cur=cur.next
return prehead.next
单链表加一
使用链表反转
我的思路:
因为在链表反转的题目中,以下就想到了链表反转
难点:
1.最后一个数如果为9,要进行拆分,这个特殊情况没有考虑到,拆分后的两个数排列也需要仔细考虑,因为还要反转链表。然后是拆分后会多出来一个,我第一次忘记直接跳出去了,拆分的前面那个数也加了一,悲伤
2.进位符号要记得每次清零啊
def plusOne(self,head):
def reverist(head):
if not head or not head.next:
return head
cur = head.next
head.next = None
while cur:
next = cur.next
cur.next = head
head = cur
cur = next
return head
head = reverist(head)
ans = 0
cur = head
cur.val = cur.val + 1
while cur:
if ans == 1:
cur.val = cur.val + 1
ans=0
if cur.val >= 10:
if cur.next==None:
next=ListNode(cur.val%10)
cur.val=cur.val/10
cur.next=next
break
else:
ans = 1
cur.val = cur.val % 10
cur = cur.next
head = reverist(head)
return head
使用栈
难点:循环不太好,写出来了却因为range取值不对错误了
代码太繁琐了,需要改进
def plusOne(self,head):
if not head :
return head
cur=head
pre=ListNode(0)
pre.next=head
s=[]
len=0
ans=1
add=0
while cur:
s.append(cur.val)
cur=cur.next
len+=1
cur = pre.next
for i in range(len-1,-1,-1):
if ans==1:
s[i]+=1
ans=0
if s[i]>=10:
if i==0:
add=1
s[i]=0
else:
s[i]=0
ans=1
for i in range(0,len):
cur.val=s[i]
cur=cur.next
if add==1:
adder=ListNode(1)
adder.next=pre.next
pre.next=adder
return pre.next
老师的方法——找9法
思路:找到最右边的不是9的数字,这是进位终止的地方
注意:必须设置虚拟结点为0,这样才可以把特殊情况也解决
def plusOne(self,head):
ans=ListNode(0)
ans.next=head
not_nine=ans
while head:
if head.val!=9
not_nine=head
head=head.next
not_nine.val+=1
not_nine=not_nine.next
while not_nine:
not_nine.val=0
not_nine=not_nine.next
return ans if ans.val else ans.next