0
点赞
收藏
分享

微信扫一扫

链表和斐波拉奇数列


  1. 链表的递归查询
  2. 链表的倒置
  3. 链表的两个节点互换
  4. 斐波拉奇数列

package third;

import java.util.Scanner;

public class Convert
{
public static void main(String[] args)
{
System.out.println("链表大小");
Scanner in = new Scanner(System.in);
int count=in.nextInt();
in.close();
NodeList<Integer> my=new NodeList<Integer>(count);

for(int x=0;x<count;x++)
{
my.give(x, x+1);
}
my.show();
my.Convert(); //链表的两个一组的交换
my.show();
NodeList<Integer> my2 =my.Recover(); //链表的倒置
my2.show();
my2.query(my2.head.next);
System.out.println("递归斐波拉奇"+new Convert().Fib(10));
}
public int Fib(int x)
{
if(x==1||x==2)
{
return 1;
}
else
{
return Fib(x-1)+Fib(x-2);
}
}
}
class NodeList <T>
{
Node<T> head;
//链表递归查询
public void query(Node<T> cur)
{
if(cur==null)
{
System.out.println("结束");
return;
}
else
{
System.out.print(cur.data+" ");
query(cur.next);
}
}
//链表的倒置
public NodeList<T> Recover()
{
NodeList<T> newhead=new NodeList<T>();
Node<T> cur=head.next;
while(cur!=null)
{
head.next=cur.next;
cur.next=newhead.head.next;
newhead.head.next=cur;
cur=head.next;
}
return newhead;
}
//链表的两个一组地交换
public void Convert()
{
Node<T> temp = head;
Node<T> odd = temp.next;
Node<T> even;
while(odd!=null)
{
even = odd.next;
if(even==null)
break;
else
{
odd.next=even.next;
even.next=odd;
temp.next=even;
temp=odd;
odd=temp.next;
}
}
}
// 这个方法有点菜
// public void Convert()
// {
// Node<T> cur=this.head;
// Node<T> cur1=null;
// while(cur!=null&&cur.next!=null&&cur.next.next!=null)
// {
// cur1=cur.next.next;
// cur.next.next=cur.next.next.next;
// cur1.next=cur.next;
// cur.next=cur1;
// cur=cur.next.next;
// }
//
// }
public NodeList()
{
this.head=new Node<T>();
}
public NodeList(int n)
{
this();
for(int x=0;x<n;x++)
{
Insert(0, new Node<T>());
}
}
public void Insert(int x,Node<T> node)
{
int falg=-1; //标志位置
Node<T> cur =head;
while(falg<x-1&&cur!=null)
{
cur=cur.next;falg++;
}
if(falg>x-1||cur==null)
{
System.out.println("a error location");
}
else
{
node.next=cur.next;
cur.next=node;
}
}

public void show()
{
Node<T> cur=this.head.next;
for(int x=0;x<length();x++)
{
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println("结束");
}
public int length()
{
Node<T> node=head.next;
int length=0;
while(node!=null)
{
node=node.next;
length++;
}
return length;
}
/*这个方法有隐患,当用户输入-1时将头节点赋值了
public void give(int index,T data)
{
Node<T> cur=this.head;
int falg=-1;
while(cur!=null&&falg<index)
{
cur=cur.next;falg++;
}
if(cur==null||falg>index)
{
System.out.println("erorr");
}
else
{
cur.data=data;
}
}*/

public void give(int index,T data)
{
Node<T> cur=this.head.next;
int falg=0;
while(cur!=null&&falg<index)
{
cur=cur.next;falg++;
}
if(cur==null||falg>index)
{
System.out.println("erorr");
}
else
{
cur.data=data;
}
}
}
class Node <T>
{
T data;
Node<T> next;
public Node()
{
super();
}
public Node(T data)
{
this.data=data;
}
}


举报

相关推荐

0 条评论