@[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();
}
}