java实现单链表的翻转
我写了一个递归的方法reverse()运行出的结果是testlinklist.Node@4aa298b7;
然后还有一个reverse2 ()的方法写到那边写不下去了 求大神教
import java.util.Scanner;
class Node {
protected int data; //数据
protected Node next; //后续
public Node(int data, Node next) {
setData(data); //设数据
setNext(next); //设后续
}
public Node(int data) {
this(data, null); //无后续
}
public Node() {
this(0, null); //无数据,无后续
}
public void setData(int data) {
this.data = data;
}
public void setNext(Node next) {
this.next = next;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
}
class LinkList {
protected Node head; // 单链表的头指针
protected int size=0;
public LinkList() { // 单链表的构造方法
head = new Node(0, null); // 初始化头结点,空表
}
public void create(int n) { //用n个数据建立链表
Scanner sc = new Scanner(System.in);
Node p = head, s;
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + i + "个结点的数据:");
s = new Node(sc.nextInt());
p.setNext(s);
p = s;
++size;
}
}
public void print() {
Node p = head.getNext(); //从有数据的开始
while (p != null) {
System.out.print(p.getData() + " ");
p = p.getNext();
}
System.out.println();
}
public void insert(int i, int x) { //插入
Node p = head; //有表头,表头相当于-1号结点
int j = -1;
while (p != null && j < i - 1) { //插到i号结点前,先要定位到i-1号结点
p = p.getNext(); //查找成功时,p是i-1号结点
++j;
} //循环结束时p=null或j>i-1或j=i-1,前两种失败
if (i < 0 || p == null) { // i<0,或i-1号结点超出链表尾
System.out.println("插入位置不合法");
} else {
Node s = new Node(x); //创建新结点
s.setNext(p.getNext()); //新结点的后续设为原i号节点
p.setNext(s); //原i-1号结点的后续设为新节点
}
}
public void remove(int i){ //删除
Node p = head;
int j = -1;
while (p.getNext() != null && j < i - 1) { //找到第i-1个结点
p = p.getNext(); //查找成功时,p是i-1号结点
++j;
}
if (i < 0 || p.getNext() == null) { // i<0或i-1号是链表尾
System.out.println("删除位置不合法");
} else {
p.setNext(p.getNext().getNext()); //变为下一个的下一个
}
}
public static Node reverse(Node head){
if(head==null||head.getNext()==null){
return head;
}
Node reverseHead=reverse(head.getNext());
head.getNext().setNext(head);
head.setNext(null);
return reverseHead;
}
public void reverse2(Node head){
for(int i=0;i<size;++i){
insert(remove);
}
}
}
public class TestLinkList {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LinkList ls = new LinkList(); //空表
Node head= new Node(0);
ls.create(5);
ls.print();
System.out.println(ls.reverse(head));
}
}