java链表的操作:1、构建空表H,插入 {a,b,,,f} 遍历输出单链表H 输出单链表H的长度
时间: 2023-12-17 17:05:33 浏览: 50
Java中链表的操作可以通过LinkedList类实现。具体的操作如下:
1. 构建空表H
```java
LinkedList<String> H = new LinkedList<String>();
```
2. 插入 {a,b,,,f}
```java
H.add("a");
H.add("b");
H.add(null);
H.add(null);
H.add(null);
H.add("f");
```
注意:因为是单链表,所以需要使用add()方法进行尾部插入,而不能使用set()方法进行指定位置插入。
3. 遍历输出单链表H
```java
for(String s : H){
System.out.print(s + "->");
}
```
输出结果为:a->b->null->null->null->f->
4. 输出单链表H的长度
```java
System.out.println("链表H的长度为:" + H.size());
```
输出结果为:链表H的长度为:6
相关问题
java链表构建单链表空表H,插入abcdef,遍历
以下是Java代码:
```java
class Node {
char data;
Node next;
public Node(char data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public void add(char data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
public class Main {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add('a');
list.add('b');
list.add('c');
list.add('d');
list.add('e');
list.add('f');
list.display();
}
}
```
输出结果为:a b c d e f
链表的操作:1、构建空表H,插入 {"a","b",",","f"} 遍历输出单链表H 输出单链表H的长度 判断单链表H是否为空 输出单链表H的第3个元素 输出元素c的位置 在第5个位置之前插入元素e后,输出单链表 删除H的第了个元素,输出单链表H
链表的操作:
1. 构建空表H
```python
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
H = ListNode()
```
2. 插入 {"a","b",",","f"}
```python
H = ListNode()
curr = H
for val in ["a", "b", ",", "f"]:
curr.next = ListNode(val)
curr = curr.next
```
3. 遍历输出单链表H
```python
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```
4. 输出单链表H的长度
```python
curr = H.next
count = 0
while curr:
count += 1
curr = curr.next
print(count)
```
5. 判断单链表H是否为空
```python
if H.next:
print("H is not empty.")
else:
print("H is empty.")
```
6. 输出单链表H的第3个元素
```python
curr = H.next
for i in range(2):
curr = curr.next
print(curr.val)
```
7. 输出元素c的位置
```python
curr = H.next
pos = 0
while curr:
pos += 1
if curr.val == "c":
print(f"Position of c is {pos}.")
break
curr = curr.next
else:
print("c is not in the list.")
```
8. 在第5个位置之前插入元素e后,输出单链表
```python
curr = H.next
pos = 0
while curr:
pos += 1
if pos == 4:
new_node = ListNode("e")
new_node.next = curr.next
curr.next = new_node
break
curr = curr.next
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```
9. 删除H的第了个元素,输出单链表H
```python
H.next = H.next.next
curr = H.next
while curr:
print(curr.val, end=" ")
curr = curr.next
```