数据结构 反转单向链表和双向链表

程序员代码面试指南(左程云)读书笔记

 第三章

反转单向链表和双向链表

//单向链表


public class Node {
 public int value;
 public Node next;
 public Node(int data){
     this.value=data;
 }
}

public class ReturnList {
public static void main(String[] args) {
    Node no1=new Node(2);
    Node no2=new Node(3);
    Node no3=new Node(4);
    Node no4=new Node(5);
    no1.next=no2;
    no2.next=no3;
    no3.next=no4;
    System.out.println(no1.value+"-"+no1.next.value+"-"+no1.next.next.value);
Node nn=    reList(no1);
System.out.println(nn.value+"-");
}

public static Node reList(Node head){
    //head如果为空,返回head
    if(head==null){
        return head;
    }
    //逆序后的第一个节点
    Node pre=null;
    Node next=null;

    while(head!=null){
        //用next保存head的next节点,然链表不会断裂
        next=head.next;
        //head的next节点指向pre
        head.next=pre;
        //交换值,做下一次反转
        pre=head;
        head=next;

    }
    return pre;
}
}
//双向链表

public class DoubleNode {
  public int value;
  public DoubleNode last;
  public DoubleNode next;
  public DoubleNode(int data){
      this.value=data;
  }
}
public class ReturnDoubleList {
  public static void main(String[] args) {

}
  public static DoubleNode reverList(DoubleNode head){
      DoubleNode pre=null;
      DoubleNode next=null;
      while(head!=null){
          next=head.next;
          head.next=pre;
          head.last=next;
          pre=head;
          head=next;
      }
      return pre;
  }
}
反转部分单向链表
   给定一个单向链表的头节点head,以及两个整数from和to,在单向链表上把第from个节点到to个节点这部分进行反转
例如:1->2->3->4->5->null  ,  form=2  to=4
     反转后: 1->4->3->2->5->null

public class Node {
 public int value;
 public Node next;
 public Node(int data){
     this.value=data;
 }
}

package com.chen.homework;

public class ReturnSomeList {
   public static void main(String[] args) {

}
   public static Node returnSomeNode(Node head,int from,int to){
       int len=0;
       Node node1=head;
       Node fPre=null;
       Node tPos=null;
       while(node1!=null){
           len++;
           fPre=len==from-1?node1:fPre;
           tPos=len==to+1?node1:tPos;
           node1=node1.next;
       }
       if(from>to || from<1 || to>len){
           return head;
       }
       node1=fPre==null?head:fPre.next;
       Node node2=node1.next;
       node1.next=tPos;
       Node next=null;
       while(node2!=tPos){
           next=node2.next;
           node2.next=node1;
           node1=node2;
           node2=next;
       }
       if(fPre!=null){
           fPre.next=node1;
           return head;
       }
       return node1;
   }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值