程序员代码面试指南(左程云)读书笔记
第三章
反转单向链表和双向链表//单向链表
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如果为空,返回headif(head==null){return head;}//逆序后的第一个节点Node pre=null;Node next=null;
while(head!=null){//用next保存head的next节点,然链表不会断裂next=head.next;//head的next节点指向prehead.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;
}
}