常见数据结构的定义
一、链表(以singly-linked list为例)
1.Java
public class ListNode{
int val;
ListNode next; //如果是双向链表,则会为left or right
ListNode(int x) {
val = x;
next = null;
}
}
2.Python
class ListNode:
def __init__(self,x):
self.val = x
self.next = Node
3.C
struct ListNode{
int val;
struct ListNode *next;
};
4.Go
type ListNode struct{
Val int
Next *ListNode
}
二、二叉树(Binary Tree Node)
1.Java
//Definition for a binary tree node
public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int x){val = x;}
}
2.python
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
3.C
struct TreeNode{
int val;
struct TreeNode *left;
struct TreeNode *right;
};
4.Go
type TreeNode struct{
Val int
Left *TreeNode
Right *TreeNode
}
三、N叉树/图
1.Java
//Definition for a Node
class Node{
public int val;
public List<Node> children; //在图中不是children,而是neighbours
public Node(){}
public Node(int _val){
val = _val;
}
public Node(int _val,List<Node> _children){
val = _val;
children = _children;
}
}
2.Python
class Node:
def __init__(self,val = None,children = None):
self.val = val
self.children = children