题目:4、链表(如图7-3所示)的每个结点定义如下:
Node {
int data;
Node next;
}
创建一个初始为10个结点的单向链表,结点数据用随机函数产生。
(1) 输出该链表:
(2)分别在首尾增加一个数据为100的结点,输出链表。 请前辈们指点一下标红处,为什么在方法里面将p赋给header就不行,在外面就可以?
import java.util.Random;public class Linklist {
public static void main(String[] args) {
Random r=new Random();
Node header=new Node(r.nextInt(100)+1);
struct(header);
print(header);
System.out.println("");
Node p=new Node(r.nextInt(100)+1);
addFront(header,p);//头部添加
header=p;//外部可以赋
print(header);
System.out.println("");
Node d=new Node(r.nextInt(100)+1);
addLast(header,d);//尾部添加
print(header);
}
//构造链表
public static void struct(Node head){
Random r=new Random();
for(int i=0;i<10;i++){
Node p=new Node(r.nextInt(100)+1);
head.next=p;
head=p;
}
}
//输出链表
public static void print(Node head){
while(head.next!=null){
System.out.print(head.data+" ");
head=head.next;
}
}
//头部添加
public static void addFront(Node head,Node p){
p.next=head;
head=p;//不能把P赋给head??
}
//尾部添加
public static void addLast(Node head,Node p){
while(head.next!=null)
head=head.next;
head.next=p;
}
}
Node {
int data;
Node next;
}
创建一个初始为10个结点的单向链表,结点数据用随机函数产生。
(1) 输出该链表:
(2)分别在首尾增加一个数据为100的结点,输出链表。 请前辈们指点一下标红处,为什么在方法里面将p赋给header就不行,在外面就可以?
import java.util.Random;public class Linklist {
public static void main(String[] args) {
Random r=new Random();
Node header=new Node(r.nextInt(100)+1);
struct(header);
print(header);
System.out.println("");
Node p=new Node(r.nextInt(100)+1);
addFront(header,p);//头部添加
header=p;//外部可以赋
print(header);
System.out.println("");
Node d=new Node(r.nextInt(100)+1);
addLast(header,d);//尾部添加
print(header);
}
//构造链表
public static void struct(Node head){
Random r=new Random();
for(int i=0;i<10;i++){
Node p=new Node(r.nextInt(100)+1);
head.next=p;
head=p;
}
}
//输出链表
public static void print(Node head){
while(head.next!=null){
System.out.print(head.data+" ");
head=head.next;
}
}
//头部添加
public static void addFront(Node head,Node p){
p.next=head;
head=p;//不能把P赋给head??
}
//尾部添加
public static void addLast(Node head,Node p){
while(head.next!=null)
head=head.next;
head.next=p;
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货