要求
给出单链表的头节点 head ,要求反转链表,并返回反转后的链表。
实现原理
单向链表反转就是将链表的指针方向改变。由于单链表没有指向前一个结点的指针,所以,我们定义一个指向前一个节点的指针pre,用于存储每一个节点的前一个结点;定义一个保存当前节点的指针cur以及下一个节点指针的next。定义好之后,遍历单链表,将next指向cur的下一个节点,将cur的next指向pre(此时链表是断开状态),pre向后移动,cur向后移动,直至遍历到最后一个结点为止。
代码实现
public class LinkedList {
public static Node reverse(Node head){
//如果链表头为null或链表只有一个节点,无需反转,直接返回
if (null == head || null == head.child){
return head;
}
// 当前节点的前一个节点
Node pre = null;
// 当前节点
Node cur = head;
// 当前节点的后一个节点
Node next = null;
while (cur != null){
next = cur.child; //next节点指向当前节点的后一个节点
cur.child = pre;//当前节点的child指向当前节点的前一个节点,反转的关键,此时链表断开
pre = cur;// 当前节点的前一节点向后移动
cur = next;// 当前节点向后移动
}
return pre;
}
public static class Node<E>{
E item;
Node child;
public Node(E item){
this.item = item;
}
}
}
测试代码
public class LinkedListTest {
LinkedList.Node node = null;
@Before
public void init(){
LinkedList.Node node1 = new LinkedList.Node(10);
LinkedList.Node node2 = new LinkedList.Node(20);
LinkedList.Node node3 = new LinkedList.Node(30);
LinkedList.Node node4 = new LinkedList.Node(40);
node = node1;
node1.child = node2;
node2.child = node3;
node3.child = node4;
}
@Test
public void testReverse(){
LinkedList.show(node);
System.out.println("----------------------");
LinkedList.Node reverseNode =LinkedList.reverse(node);
LinkedList.show(reverseNode);
}
}