找出一个单向链表的起始位置

package LinkedList;


public class Circle {
public static void main(String[] args) {
LNode linkedNode1 = new LNode();
linkedNode1.val = 1;
LNode linkedNode2 = new LNode();
linkedNode2.val = 2;
LNode linkedNode3 = new LNode();
linkedNode3.val = 3;
LNode linkedNode4 = new LNode();
linkedNode4.val = 4;
linkedNode1.next = linkedNode2;
linkedNode2.next = linkedNode3;
linkedNode3.next = linkedNode4;
linkedNode4.next = linkedNode2;
LNode l = begin(linkedNode1);
System.out.println("--单向链表的起始位置->" + l.val);
}


public static LNode begin(LNode linkedNode) {
LNode p = linkedNode.next;
LNode q = linkedNode.next.next;
while (q != null) {
if (p == q) {
break;
} else {
p = p.next;
q = q.next.next;
}


}


q = linkedNode;
while (q != null) {
if (p == q)
return p;// 返回环中入口结点
p = p.next;
q = q.next;
}


return null;
}


}


class LNode {
public int val;
public LNode next;
}
在C语言中,创建一个单向链表通常涉及以下几个步骤: 1. **定义节点结构**: 首先,你需要定义一个节点结构体,包含数据域(如`data`)和指向下一个节点的指针(如`next`)。 ```c struct Node { int data; // 数据域 struct Node* next; // 指向下一个节点的指针 }; ``` 2. **创建链表头节点**: 创建链表的第一步通常是创建一个空的头节点(如果有的话),用于表示链表的开始。 ```c struct Node* head = NULL; ``` 3. **添加节点**: 你可以定义一个函数来插入新节点到链表中,例如: - 插入到链表的末尾: ```c void append(struct Node** head, int data) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (newNode == NULL) { printf("Memory allocation failed.\n"); return; } newNode->data = data; newNode->next = NULL; if (*head == NULL) { *head = newNode; return; } struct Node* temp = *head; while (temp->next != NULL) { temp = temp->next; } temp->next = newNode; } ``` - 插入到指定位置: ```c void insertAtPosition(struct Node** head, int data, int position) { // ... 实现代码,检查边界条件、分配内存并插入等 } ``` 4. **遍历链表**: 可以编写一个函数来打印链表的所有元素: ```c void printList(struct Node* node) { while (node != NULL) { printf("%d -> ", node->data); node = node->next; } printf("NULL\n"); } ``` 5. **释放内存**: 当不再需要链表时,记得释放所有节点的内存以避免内存泄漏: ```c void destroyList(struct Node** head) { struct Node* current = *head; struct Node* next; while (current != NULL) { next = current->next; free(current); current = next; } *head = NULL; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值