且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-25 18:10:54

在LeetCode中看到判断回文的程序:https://leetcode.com/problems/palindrome-linked-list/

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

 

反转单链表的代码如下:

在O(n) 时间复杂度,O(1)空间复杂度内反转单链表
 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      }