数据结构-java与c实现带头结点的单链表

前言:数据结构实验课上老师布置了一个关于链表的任务,听到很多同学在说数组什么的,又是语法错误什么,所以写下这篇文章来理一下思路,由于博主为java发展方向,所以更喜欢在java语言背景下去理解他。

题目:设顺序表va中的数据元素递增有序,试写一算法,将x插入到顺序表的适当位置上,以保持该表的有序性。

首先博主认为链表是数组的一种重要的替代方式,所以在实现最基本的链表时同学们提到初始化一个数组什么的,我也表示很困惑。

上代码:

c语言实现:
struct st
{
    int data;
    struct st *next;
};
struct st *insenode(struct st *head,int x)
{
    struct st *new,*last,*current;
    new =(struct st *)malloc(sizeof(struct st));
    new->data=x;
    current=head;
    while(x>current->data && current->data!=null)
    {
        last=current;
        current=current->next;
    }
    if(x<=current->data)
    {
        if(current==head)
        {
            new->next=head;
            head=new;
        }
        else
        {
            new->next=current;
            last->next=new;

        }
    }
    else
    {
        new->next=null;
        current->next=new;
    }
    return(new);
}


java中StackAPI的实现依赖于以下基础的理解,对于一些校招面试Java的同学来说LinkedList类内部实现问到的频率也是相当高的

java实现:
import java.util.Scanner;

class Node {
	int data;
	Node next;
}

public class stack {
	public static void main(String[] args) {
		Node first = new Node();
		Node second = new Node();
		Node third = new Node();
		Node last = new Node();

		first.data = 1;
		second.data = 5;
		third.data = 9;
		last.data = 13;

		first.next = second;
		second.next = third;
		third.next = last;
		// last.next为null,现在我们就构造了一条最简单的链表;
		
		for (Node y = first; y != null; y = y.next) {// 打印初始链表
			System.out.print(y.data + " ");
		}
		
		// 以下代码为在该链表中插入一个元素
		Scanner sc = new Scanner(System.in);
		Node node = new Node();// 要插入元素所处的节点类
		node.data = sc.nextInt();
		
	
		
		
		if (node.data <= first.data) {// 头节点插入
			Node oldfirst = first;
			first = new Node();
			first.data = node.data;
			first.next = oldfirst;

		}

		else if (node.data > last.data) {// 尾节点插入
			Node oldlast = last;
			last = new Node();
			last.data = node.data;
			oldlast.next = last;
		} else { // 链表遍历
			for (Node x = first; x != null; x = x.next) {
				if (x.data < node.data && x.next.data >= node.data) {
					node.next = x.next;
					x.next = node;
				}

			}
		}

		for (Node y = first; y != null; y = y.next) {// 打印新链表
			System.out.print(y.data + " ");
		}

	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值