数据结构--线性链表的实现Java

一、线性链表:用一组任意的存储单元存储线性表的数据元素

结点表示:class LNode{

                          int data;

                          LNode next;

                         }

二、代码理解

import java.util.*;
class LNode{
 int data;
 LNode next;
 Scanner in = new Scanner(System.in);
 public LNode(int data) {                         //创建一个结点
  this.data = data;
 }
 
 public void createList(LNode L,int n) {   //创建一个长度为n的链表,头节点为L
  L.next  = null;
  for(int i = 1;i<n;i++) {
   LNode P = new LNode(in.nextInt());
   L.next = P;
   L =L.next;
  }
 }
 
 public LNode getElem(LNode L,int i) {            //在链表L中查找第i个元素的值
  LNode P = L.next;
  int j = 1;
  while((P!=null)&&j<i) {
   P = P.next;
   ++j;
  }
  return P;
 }
 
 public void ListInsert(LNode L,int i,LNode e) {   //在链表L中第i个位置插入元素e
  
  LNode P = L.next;
  int j = 1;
  while((P!=null)&&j<i) {
   P = P.next;
   ++j;
  }
  e.next = P.next;
  P.next = e;
 }
 
 public void ListDelet(LNode L,int i) {                    //在链表L中删除第i个结点
  LNode P = L.next;
  int j = 1;
  while((P!=null)&&j<i) {
   P = P.next;
   ++j;
  }
  P.next = P.next.next;
 }
}
public class LinkedLists {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  LNode L = new LNode(10);
  L.createList(L, 10);                        //创建长度为n的链表
  LNode P = L.next;
  for(int i = 1;i<=10;i++) {            //遍历链表
   System.out.print(P.data+" ");
   L = P.next;
  }
LNode n = L.getElem(L, 5);           //查找第5个结点
  System.out.println();
  System.out.print(n.data);
 }
}

输入:1 2 3 4 5 6 7 8 9
输出:1 2 3 4 5 6 7 8 9 

          5

三、单链表的自反

 public static Nodes reverseList(Nodes head) {
  Nodes pre = null;
  Nodes next = null;
  while(head!=null) {
   next = head.next;
   head.next = pre;
   pre = head;
   head = next;
  }
  return pre;
 }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值