# 数据结构与算法之单向链表

## 基本介绍

1. 链表是以结点的方式来存储的
2. 每个结点包含data域和next域
3. 每个结点不一定连续
4. 带有头结点或不带有头结点

## 代码示例

private Node head = new Node(0,"");

while(temp.getNext() != null){
temp = temp.getNext();
}
temp.setNext(n);
}

while(temp.getNext() != null){
if(temp.getNext().getId() > n.getId()){
break;
}else if(temp.getNext().getId() == n.getId()){
System.out.println(n.getId()+"已存在，无法添加");
return;
}
temp = temp.getNext();
}
n.setNext(temp.getNext());
temp.setNext(n);
}

public void updateById(Node n){
boolean flag = false;
while(temp.getNext() != null){
if(temp.getNext().getId() == n.getId()){
flag = true;
break;
}
temp = temp.getNext();
}
if(!flag){
System.out.println("没有该ID存在");
return ;
}
Node last = temp.getNext().getNext();
temp.setNext(n);
n.setNext(last);
}

public void delById(int id){
boolean flag = false;
while(temp.getNext() != null){
if(temp.getNext().getId() == id){
flag = true;
break;
}
temp = temp.getNext();
}
if(!flag){
System.out.println("没有该ID存在");
return ;
}
temp.setNext(temp.getNext().getNext());
}

public void list(){
System.out.println("链表为空");
return;
}
while (temp.getNext() != null){
System.out.println(temp = temp.getNext());
}
}
}

class Node{
private String name;

private Node next;

private int id;

public Node(int id,String name) {
this.name = name;
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Node getNext() {
return next;
}

public void setNext(Node next) {
this.next = next;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
}

### 常见问题

1. 求单链表的有效节点个数
public int size(){
int size = 0;
while (temp.getNext() != null){
temp = temp.getNext();
size++;
}
return size;
}
1. 查找单链表的倒数第K个结点
public Node getByLastIndex(int i){
int index = size() - i + 1;
if(index <= 0 || index > size()){
throw new RuntimeException("没有该位置");
}
int count = 0;
while (count ++ != index){
temp = temp.getNext();
}
return temp;
}
1. 反转
public void reverse(){
return;
}
while (cur != null){
Node next = cur.getNext();
cur = next;
}
}
1. 从尾到头打印单链表
public void listReverse(){
}

private void print(Node node){
if(node.getNext() != null){
print(node.getNext());
}
System.out.println(node);
}
}
1. 合并两个有序的单链表，合并后依然有序
if(list == null){
throw new RuntimeException("不能为null");
}
return;
}
Node[] nodes = new Node[list.size()];
for(int i = 0; i < list.size() ; i++){
nodes[i] = next;
next = next.getNext();
}
for (Node node : nodes) {
}
}

11-12 139

03-21 210

12-18 674

09-17 163

09-23 648

02-21 1461

12-01 3091

04-08 980

06-08 778

04-05 1114

03-21 199

12-03 82

10-12 56

12-25 6859

08-26 54

03-01 636

10-04 730

04-18 5607

08-13 4067

03-11 8879

03-19 82万+

04-14 60万+

02-28 9300

03-01 14万+

03-08 7万+

04-25 7万+

03-10 13万+

03-10 19万+

03-12 12万+

03-13 12万+

#### 我入职阿里后，才知道原来简历这么写

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客