public class Test {
public static void main(String[] args) {
try{
LinkList list1 = new LinkList()
LinkList list2 = new LinkList()
LinkList list3 = null
list1.addAt(0, new Item(1, 5))
list1.addAt(1, new Item(-1.5, 3))
list1.addAt(2, new Item(1, 1))
list2.addAt(0, new Item(0.5, 5))
list2.addAt(1, new Item(0.5, 4))
list2.addAt(2, new Item(1.5, 3))
list2.addAt(3, new Item(3, 0))
list3 = mergeLinkList(list1, list2)
System.out.println("一元多项式的相加过程:")
list1.listAll()
System.out.println(" + ")
list2.listAll()
System.out.println(" = ")
list3.listAll()
}
catch(Exception e){
e.printStackTrace()
}
}
/**
* 一元多项式的一般项类
*/
class Item{
private double coef //一元多项式的一般项的系数
private int exp //一元多项式的一般项的指数
public Item(){
this.coef = 0.0
this.exp = 0
}
public Item(double coef, int exp){
this.coef = coef
this.exp = exp
}
public double getCoef(){
return this.coef
}
public void setCoef(double coef){
this.coef = coef
}
public int getExp(){
return this.exp
}
public void setExp(int exp){
this.exp = exp
}
}
/**
* 链表结点类
*/
class Node{
private Item data
private Node next //链表结点的指针域,指向直接后继结点
public Node(){
data = null
next = null
}
public Node(Item data, Node next){
this.data = data
this.next = next
}
public Item getData(){
return this.data
}
public void setData(Item data){
this.data = data
}
public Node getNext(){
return this.next
}
public void setNext(Node next){
this.next = next
}
}
/**
* 链表类
*/
class LinkList{
private Node head = null//头结点指针
private int size = 0
public LinkList(){
head = new Node()
size = 0
}
//在i位置插入元素elem
public boolean addAt(int i, Item elem) {
if(i <0 || i >size){
return false
}
Node pre,curr
int pos
for(pre=headi>0 &&pre.getNext()!=nulli--,pre=pre.getNext())
curr = new Node(elem, pre.getNext())
pre.setNext(curr)
size++
return true
}
//删除i位置的元素
public boolean removeAt(int i) {
if(i <0 || i >= size){
return false
}
Node pre,curr
for(pre=headi>0 &&pre.getNext()!=nulli--,pre=pre.getNext())
curr = pre.getNext()
pre.setNext(curr.getNext())
size--
return true
}
java是一种可以撰写跨平台应用软件的面向对象的程序设计语言。Java 技术具有卓越的通用性、高效性、平台移植性和安全性,广泛应用于PC、数据中心、游戏控制台、科学超级计算机、移动电话和互联网,同时拥有全球最大的开发者专业社群。你的问题很好理解。但是你的代码问题严重。1、你想用java代码实现还是c代码实现?从你的代码看是c语言
2、第一段代码中的结构体nod是不是应该写成Node?
3、inset函数中,链表L是有变化的,所以要用指针。结点s是不改变的,所以不应该用指针
4、既然s不是用指针,后面的s->next自然也不能这么写了。
代码:
// 删除下标为index的节点public void remove(int index) {
if (index >= modCount) {
// 抛异常
System.out.println("indexOutOfBoundsException!")// 最好自定义异常抛出,这里演示
return
}
Node node = head
// 如果节点为第一个节点
if (index == 0) {
head = head.next // 将头节点指向第二个节点
modCount--
return
}
// 如果节点为最后一个节点,找到最后一个节点的前一个节点,不用管
if (index == modCount - 1) {
System.out.println("ddd")
// 找到最后一个节点的前一个节点
int j = 0
while (node != null && j < index - 1) {
// 最后一个节点的前一个节点
node = node.next
j++
}
last = node // 最后一个节点设置为前一个节点
modCount--
return
}
// 如果节点为中间节点
int j = 0
while (node != null && j < index - 1) {
// 查找被删除的节点的前一个节点
node = node.next
j++
}
node.next = node.next.next // 被删除节点的下一个节点设置为被删除节点的下下个节点
modCount--
}