問題:翻轉一個鏈表:
給出一個鏈表1->2->3->null,這個翻轉后的鏈表為3->2->1->null
思路:看到網路上有提供兩三個思路,一是從已知鏈表里面挨個取出node,再單獨建立一個列表。
二是在原來列表的基礎上,進行類似于冒泡排序的過程,只是不參與大小比較,逢比較必換位。
我個人更看好第二種,這種方式空間復雜度小,重點在于指針的運用和如何控制已經完成翻轉的node不參與接下來的翻轉。
Python
def reverse(self, head):
# write your code here
if head == None or head.next == None:
return head
# set a variable to limit the number of exchange
m = 100
while m > 0:
# record the number of exchange
n = 0
# a pointer point to the main exchanger
flexible_head = head
# refresh the head of the list
head = head.next
# record the left node of flexible_head
last_node = None
# exchange two adjacent node position
while flexible_head.next != None and n < m:
# the right node of flexible_head
next_node = flexible_head.next
# move flexible_head to the right of next_node
flexible_head.next = next_node.next
next_node.next = flexible_head
# link last_node to the next_node
if last_node == None:
last_node = next_node
else:
last_node.next = next_node
# refresh the left node of flexible_head
last_node = next_node
# add 1 to n means there is an exchange occuring
n +=1
# reduce the length of unprocessed list
m = n - 1
return head
java
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if(head == null || head.next == null)
{
return head;
}
int val_temp;
int length=0;
ListNode current=head;
ListNode next=head.next;
while(current!=null) {
++length;
current=current.next;
}
for (int i=length-1;i>0;--i){
current=head;
next=head.next;
for (int j=0;j<i;j++){
val_temp=next.val;
next.val=current.val;
current.val=val_temp;
current=next;
next=next.next;
}
}
return head;
}
}
在我的思路里,我一直是在改變每個node的引用,實現(xiàn)node的位置變化,但是我的一個師兄提出可以交換值,這樣方便,而且在做項目的時候,值域往往是一個一個對象,所以交換起來會很方便。