//无论单链表还是双链表,节点插入都遵循先立后破的原则,即新节点指针先指向原有节点,然后再将原有节点指针指向新节点
//操作时,需要注意链表的头尾节点
import java.util.*;
import java.io.*;
//头结点,链表是否为空,当前节点,链表长度,添加节点,
public class linklist{
public int len=1;//可以没有
public Node head;//必须有头结点属性,有了头结点啥都好办
/*插入一个节点,位置为链表头节点之后,*/
void add(Node e){
if (this.head==null) {//检查是否为空,若为空添加节点为头节点
this.head=e;
}
else if (this.head.next==null) {//检查节点数是否大于2,若否,添加节点为第二个节点
head.next=e;
this.len++;
}
else {//添加节点到头结点之后
e.next=this.head.next;
this.head.next=e;
this.len++;
}
}
/*获取链表的长度, 假设链表没有len属性*/
int GetLen( ){//或int GetLen(linklist list)
int length=1;
if (this.head==null) {
length=0;
}
Node current=this.head;
while (current.next!=null) {
length++;
current=current.next;
}
return length;
}
/*查找链表倒数第k个节点,若要求不能求链表长度,则需要两个指针,两者偏移K(详见参考博客)*/
Node FindNode(int k){
int len = this.GetLen();//链表长度
Node current =this.head;
for (int i=0; i<len-k; i++) {
current=current.next;
}
return current;
}
/*合并两个有序的单链表,合并之后的链表依然有序【出现频率高】(剑指offer,题17)*/
public Node MergeNode(Node e1,Node e2){//返回链表头结点
Node current1=e1;
Node current2=e2;
Node head=current1.data<current2.data? current1:current2;//先把头结点放入新链表
current1=current1.next;
current2=current2.next;
Node current=head;
while (current1.next!=null && current2.next!=null) {//若两个链表都不为空,比较两个链表的元素,把小的放入新链表
if (current1.data<current2.data) {//if..else即可,无需while
current.next=current1;//这里注意理解
current1=current1.next;
current=current.next;
}
else {
current.next=current2;
current2=current1.next;
current=current.next;
}
}
if (current1.next!=null ) {
current.next=current1;
}
if (current2.next!=null ) {
current.next=current2;
}
return head;
}
/*打印单链表*/
public void Print(){
Node current=this.head;
for (int i=0; i<this.GetLen(); i++) {
System.out.println(current.data);
current=current.next;
}
}
/*单链表反转*/
public Node Inverse(){
Node e1=this.head;//Node e1=new Node();//这样不对,因为你的Node类中构造方法必须传参数
Node current=this.head;
current=current.next;
while(current!=null){
Node e=current;//新建一个节点,临时节点
e.next=e1;//新建节点的next指向l新链表当前头结点e1
e1=e;//调整链表的头结点
current=current.next;
/* next = current.next; //暂时保存住当前结点的下一个结点,因为下一次要用
current.next = e1; //将current的下一个结点指向新链表的头结点
e1 = current;
current = next; // 操作结束后,current节点后移 */
}
return e1;//返回头结点
}
/*测试*/
public static void main(String[] args){//测试,初始化一个链表
linklist list1=new linklist();//创建链表对象
linklist list2=new linklist();
linklist list12= new linklist();
for (int i=8; i<15; i++) {
list1.add(new Node(i));
}
for (int i=3; i<8; i++) {
list2.add(new Node(i));
}
//Node e1 =list1.head;
//Node e2=list2.head;
// Node e=list12.MergeNode(e1,e2);
// list12.head=e;
list1.Inverse();
list1.Print();
//list12.Print();
//System.out.println("链表长度:"+list12.GetLen());//获取链表长度
//System.out.println(list1.GetLen());//查找倒数第3个节点,并输出节点元素list1.GetLen()+
//System.out.println("合并的链表头结点:"+e.data);//获取链表长度
}
}
单链表
最新推荐文章于 2024-10-06 12:03:03 发布