Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1782191
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2018-04-13 11:33:54

1..

reverse a singly-linked-list , given the head, return the new head .

在C语言里面这个题就是纯粹的指针问题.


点击(此处)折叠或打开

  1. class Node:
  2.     __slots__='element','next'
  3.     
  4.     def __init__(self,element,next=None):
  5.         self.element=element
  6.         self.next=next
  7.     
  8.     def __str__(self):
  9.         return repr(self.element)

  10. #reverse a singly-linked-list , given the head, return the new head .
  11. def reverse_ll(head):
  12.     current = head
  13.     next = None
  14.     prev = None
  15.     
  16.     while current != None :
  17.         next = current.next
  18.         
  19.         current.next = prev
  20.         
  21.         prev = current
  22.         current = next
  23.     
  24.     return prev

  25. def test_reverse():
  26.     a=Node(1)
  27.     b=Node(2)
  28.     c=Node(3)
  29.     d=Node(4)
  30.     a.next=b
  31.     b.next=c
  32.     c.next=d
  33.     
  34.     #print as 1 2 3 4
  35.     head = a
  36.     while head !=None:
  37.         print(head,end='\t')
  38.         head=head.next
  39.     
  40.     print()
  41.     #reverse will get printed as 4 3 2 1
  42.     newhead = reverse_ll(a)
  43.     
  44.     while newhead != None:
  45.         print(newhead,end ='\t')
  46.         newhead = newhead.next
  47.     
  48.     
  49. test_reverse()

2. .

find nth Node from end
找出倒数第几个node的值,其实就是两个指针,前后两个指针距离为n-1,当后面指针指向最后一个Node的时候,前面的指针就指向了倒数第n个node.

点击(此处)折叠或打开

  1. def nth_elem_from_end(head, n):
  2.     left = head
  3.     right = head
  4.     
  5.     for i in range(n-1):
  6.         if right.next is None:
  7.             return None
  8.         right = right.next
  9.     while right.next is not None:
  10.         right = right.next
  11.         left = left.next
  12.     return left

  13. def test_nth_elem_from_end():
  14.     a=Node(1)
  15.     b=Node(2,a)
  16.     c=Node(3,b)
  17.     d=Node(4,c)
  18.     e=Node(5,d)
  19.     
  20.     #current order : head=e->d->c->b->a
  21.     
  22.     target_node = nth_elem_from_end(e,2)
  23.     print(target_node)


阅读(909) | 评论(0) | 转发(0) |
0

上一篇:Python_Array_Problems_3

下一篇:Python_Tree_Problems

给主人留下些什么吧!~~