设有一个带头结点的单循环链表,请写出完整代码实现从这个链表中删除值为x的结点。若链表中没有值为x的结点,则打印“没有找到该结点”
时间: 2023-09-08 15:05:20 浏览: 128
### 回答1:
```
typedef struct Node {
int data;
struct Node *next;
} Node, *LinkedList;
void deleteNode(LinkedList L, int x) {
Node *p = L->next;
Node *pre = L;
while (p != L) {
if (p->data == x) {
pre->next = p->next;
free(p);
printf("删除成功\n");
return;
}
pre = p;
p = p->next;
}
printf("没有找到该结点\n");
}
```
### 回答2:
以下是完整代码实现从单循环链表中删除值为x的结点的示例代码:
```python
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
def delete_node(head, x):
if head is None:
print("没有找到该结点")
return head
current = head
prev = None
found = False
# 遍历链表寻找待删除结点
while True:
if current.next is head:
break
if current.value == x:
found = True
break
prev = current
current = current.next
if not found:
print("没有找到该结点")
return head
# 删除结点
if current is head and current.next is head: # 链表只有一个结点的处理
head = None
elif current is head: # 待删除结点为头结点的处理
prev = head
while prev.next is not head:
prev = prev.next
prev.next = current.next
head = current.next
else: # 其他结点的处理
prev.next = current.next
return head
# 测试代码
if __name__ == "__main__":
# 创建一个带头结点的单循环链表
head = ListNode(None)
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
head.next = node1
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = head
# 删除结点值为3的结点
head = delete_node(head, 3)
# 打印删除后的链表
current = head.next
while current is not head:
print(current.value, end=" ")
current = current.next
print()
```
该代码实现了在一个带头结点的单循环链表中删除值为x的结点。如果链表中没有值为x的结点,则会打印"没有找到该结点"。
### 回答3:
具体代码如下:
```python
# 定义链表节点类
class Node:
def __init__(self, value):
self.value = value
self.next = None
# 定义循环链表类
class CircularLinkedList:
def __init__(self):
self.head = Node(None)
self.head.next = self.head
def addNode(self, value):
newNode = Node(value)
if self.head.next == self.head:
self.head.next = newNode
newNode.next = self.head
else:
curNode = self.head.next
while curNode.next != self.head:
curNode = curNode.next
curNode.next = newNode
newNode.next = self.head
def deleteNode(self, x):
if self.head.next == self.head:
print("没有找到该结点")
return
preNode = self.head
curNode = self.head.next
while curNode != self.head:
if curNode.value == x:
preNode.next = curNode.next
return
preNode = curNode
curNode = curNode.next
print("没有找到该结点")
def printList(self):
if self.head.next == self.head:
print("链表为空")
return
curNode = self.head.next
while curNode != self.head:
print(curNode.value, end=" ")
curNode = curNode.next
print()
# 测试代码
if __name__ == "__main__":
linkedList = CircularLinkedList()
linkedList.printList() # 链表为空
linkedList.addNode(1)
linkedList.addNode(2)
linkedList.addNode(3)
linkedList.addNode(4)
linkedList.printList() # 1 2 3 4
linkedList.deleteNode(3)
linkedList.printList() # 1 2 4
linkedList.deleteNode(5) # 没有找到该结点
```
该代码首先定义了一个链表节点类Node,包含值和指向下一个节点的指针。然后定义了循环链表类CircularLinkedList,包含头节点和相应的操作方法。其中, `addNode`方法用于向链表中添加节点,`deleteNode`方法用于删除值为x的节点。最后,测试了从链表中删除节点的功能。
阅读全文