问题:翻转一个链表:
给出一个链表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的引用,实现node的位置变化,但是我的一个师兄提出可以交换值,这样方便,而且在做项目的时候,值域往往是一个一个对象,所以交换起来会很方便。