单链表定义与创建

 @[TOC]

1. 单链表的定义与创建,c++版

#include<iostream> 

using namespace std;


struct ListNode {
	int val;
	struct ListNode *next;
//	ListNode(int x) :
//	val(x), next(NULL) {
//	}
};

void createList(ListNode* pHead){
	ListNode*p = pHead;   //将pHead的地址赋予一个类的新指针p,此时p的地址与pHead的地址一样
	for(int i =1; i <10; ++i){
		ListNode* pNewNode = new ListNode; //创建一个类的新指针pNewNode,作为中间过程为以后存放新节点提供过渡
		pNewNode -> val = i;     
		pNewNode -> next = NULL;   //为新节点分配内存,初始化类成员
		
		p -> next = pNewNode;   //上一结点指向这个新建立的结点 
		p = pNewNode;     //p节点指向这个新结点 
	}
}



int main(){
	
	void createList(ListNode* pHead);
	
	ListNode *head = NULL;  //定义了一个ListNode结构类head的指针,指向链表的第一个节点,并初始化;
    head = new ListNode;   
	head -> val = 0;  
	head -> next = NULL;   //为head分配内存,初始化类成员
	
	createList(head); 
	
}

单链表定义与创建__Java版

package lianbiao;

public class Node {
	protected Node next;  
	protected int data;
	
	public Node(int data) {  //构造函数传参
		this.data = data;
		this.next = null;
	}
	public Node() {}
	
	public void add(int newdata) {
		Node newNode = new Node(newdata);  //创建新节点
		if(this.next == null) {
			this.next = newNode;  //单前链表尾null,链接至链表尾	
		}else {
			this.next.add(newdata); //空链表则 创建
		}
		
	}
	
	public void print() {
		System.out.println(this.data + "-->");
		if(this.next != null) {
			this.next.print();
		}
	}
	
	public static void main(String[] args) {
		Node l1 = new Node(1);
		l1.add(2);
		l1.add(3);
		l1.print();
		
	}

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值