/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
//该方法存取了三个节点,防止链表中断
public class Solution {
/*
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
if(head==null){
return null;
}
ListNode temp = head;
ListNode temp1 = null;
ListNode temp2 = null;
if(head.next!=null){
temp1 = head.next;
if(head.next.next!=null){
temp2 = head.next.next;
}
}
head.next = null;
while(temp2!=null){
temp1.next = head;
head = temp1;
temp1 = temp2;
temp2 = temp2.next;
}
if(temp2 == null){
if(temp1!=null){
temp1.next = head;
head = temp1;
}
}
return head;
}
}
还有一种方法更为简单。就是将链表每一个元素存入栈中,然后进行操作,但是会浪费空间,lintcode不让通过