Java语言中链表的创建、遍历、逆置
class ListNode
{
int val;
ListNode next;
}
public class testListNode {
/**
* 1.链表的创建
* 2.链表的遍历
* 3.链表的逆置
*
*
*/
public static void main(String[] args) {
ListNode l=Create();
Print(l);
ListNode p=Reverse(l);
Print(p);
}
//1.创建一个链表
public static ListNode Create()
{
ListNode head,p,q;
p=new ListNode();
q=new ListNode();
Scanner sc=new Scanner(System.in);
p.val=sc.nextInt();
head=null;
int n=0;
while(p.val!=0)
{
n++;
if(n==1)
{
head=p;
}
else
{
q.next=p;
q=p;
p=new ListNode();
p.val=sc.nextInt();
}
}
q.next=null;
return head;
}
//2.遍历一个链表
public static void Print(ListNode head)
{
ListNode p=head;
while(p!=null)
{
System.out.print(p.val+" ");
p=p.next;
}
System.out.println();
}
//3.逆置链表
public static ListNode Reverse(ListNode head)
{
ListNode p,q,r;
p=head;
q=p.next;
while(q!=null)
{
r=q.next;
q.next=p;
p=q;
q=r;
}
head.next=null;
head=p;
return head;
}
}