您的位置:首页 > 其它

在O(n) 时间复杂度,O(1)空间复杂度内反转单链表

2015-07-28 17:31 423 查看
在LeetCode中看到判断回文的程序:https://leetcode.com/problems/palindrome-linked-list/

里面用单链表来存储数据,先反转前半部分的单链表,然后分别从 表头 和 中间链表位置处 开始比较元素。

反转单链表的代码如下:

1      private ListNode reverseList(ListNode head, int length){
2          if(head == null)
3              return null;
4          ListNode currentNode, preNode;
5          currentNode = preNode = head;
6          ListNode nextNode = head.next;
7          head.next = null;
8          for(int i = 1; i < length; i++){
9              if(nextNode != null){
10                  currentNode = nextNode;
11                  nextNode = nextNode.next;
12                  currentNode.next = preNode;
13                  preNode = currentNode;
14              }
15          }
16         return currentNode;
17      }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: