单向链表反转

先创建一个单向链表

/**
 * 单向链表 * * */class Node{
    public Node(int value){
        this.value = value;
 }
    public int value;
 public Node next;
}
  • 头插法

头插法使用双指针方式进行头插

/**
 * 方式1 * @param head
 * @return
 */
public  static Node reverse1(Node head){
    /**
 * 判断当前节点是否为空或者仅有一个节点 
 */ 
 if (head == null || head.next == null) {
        return head;
 }
 //记录上一个cur的节点
 Node pre = null;
 //记录当前节点的下一个节点
 Node post;
 while (head!=null){
 //把post节点前移
 post = head.next;
 //当前节点的下一个节点指向上一次的当前节点
 head.next = pre;
 //把当前节点赋值给pre,用于下次使用
 pre = head;
 //把当前节点前移
 head = post;
 }
    //由于最后循环中 head = post已经做了前移,所以此处取pre为反转后的链表
 return pre;
}
  • 递归反转

/**
 * 方式2,递归 * @param head
 * @return
 */
public  static Node reverse2(Node head){
 /**
 * 判断当前节点是否为空或者仅有一个节点 
 */ 
 if (head == null || head.next == null) {
        return head;
 }
 /**
 * 递归方式获取下一个节点,最底层返回的node为链表的尾部 
 */
 Node node = reverse2(head.next);
 /**
 * 此处进行反转
 */ 
 head.next.next = head;
 head.next = null;
 return node;
}

小施主
0 声望0 粉丝