Java單鏈表增刪改查反轉基本操作

2021-08-08 14:01:45 字數 1954 閱讀 6319

資料結構複習,**是最好的說明。

節點類:

public class node 

public object getobject()

public void setobject(object object)

public node getnext()

public void setnext(node next)

}

鍊錶類:

public class singlelinkedlist 

/*** 頭插入

* @param o

*/public void addnewhead(object o)

/*** 頭刪除

*/public void deletehead()

head=head.getnext();

size--;

}/**

* 指定index插入

* @param index

* @param object

*/public void add(int index,object object)

if (index==0)

node temp=head;

while (index>1)

node node=new node(object);

node.setnext(temp.getnext());

temp.setnext(node);

size++;

}/**

* 指定index刪除,修改、查詢方法同理

* @param index

*/public void delete(int index)

if (index==0)

node temp=head;

while (index>1)

temp.setnext(temp.getnext().getnext());

size--;

}/**

* 尾插入

* @param o

*/add(size,o);

}/**

* 順序輸出、逆序壓棧

*/public void printallnode()

node temp = head;

while (temp.getnext()!=null)

system.out.print(temp.getobject().tostring());

system.out.println();

}/**

* 遞迴反轉,思想:右節點遞迴,左右節點指向反轉

* @return

*/public node reverser(node head)

node reversedhead=reverser(head.getnext());

head.getnext().setnext(head);

head.setnext(null);

return reversedhead;

}/**

* 遍歷反轉,利用前節點、當前節點、後節點遍歷鍊錶,每次前節點與當前節點指向反轉,最後頭尾反轉

*/public void reverse()

node pre = head;

node cur = head.getnext();

node next;

while (cur!=null)

head.setnext(null);

head = pre;

}public node gethead()

public void sethead(node head)

public int getsize()

public void setsize(int size)

}

鍊錶反轉有參考

如有錯誤,歡迎糾正!

單鏈表增刪改查

include include include include using namespace std struct node node int x,node next null 帶參初始化 建立煉表頭結點,新增引用因為要改變指標的位址指向 void createlink node head 新增鍊...

單鏈表增刪改查

單鏈表單鍊錶 linked list 由各個記憶體結構通過乙個 next 指標鏈結在一起組成,每乙個內 存結構都存在後繼記憶體結構 鏈尾除外 記憶體結構由資料域和 next 指標域組成。單鏈表實現圖示 解析 data 資料 next 指標,組成乙個單鏈表的記憶體結構 第乙個記憶體結構稱為 鏈頭,最後...

單鏈表 增刪改查

目錄基本面試題 class heronode class singlelinkedlistpublic void add heronode heronode public void addbyorder heronode heronode if temp.next.no heronode.no el...