单链表反转是笔试面试中考察最多的算法之一,是单链表里必须要熟练掌握的算法。
/**
* @author Gavenyeah
* @date Start_Time:2016年4月1日 上午11:38:18
* @date End_Time:2016年4月1日 上午11:46:13
*/
public class ReverseSingleList {
public static void main(String args[]){
Node head=ListNode.getSingleList();
ListNode.printList(head);
head=new ReverseSingleList().reverseSingleList(head);
ListNode.printList(head);
}
public Node reverseSingleList(Node head){
if(head== null||head. next== null){
return head;
}
Node preNode=head;
Node pNode=head. next;
Node markNode=head. next;
head. next= null; //一定要断开head节点的next节点,不然形成了循环
while(markNode!= null){
markNode=markNode. next;
pNode. next= preNode;
preNode=pNode;
pNode=markNode;
}
return preNode;
}
}
代码中调用的Node类和ListNode类,代码详见
Java单链表基本操作(一)–顺序查找