根据输入的数据建立链表,并输出该链表中倒数第二个结点的数据 C语言代码实现
时间: 2023-06-10 21:03:52 浏览: 103
cpp代码-输入一个链表,输出该链表中倒数第k个结点。
以下是实现该功能的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createLinkedList(int n) {
struct Node* head = NULL;
struct Node* tail = NULL;
int data;
for (int i = 0; i < n; i++) {
printf("Enter node data: ");
scanf("%d", &data);
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
if (head == NULL) {
head = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
return head;
}
int getNthFromEnd(struct Node* head, int n) {
struct Node* temp = head;
int length = 0;
while (temp != NULL) {
length++;
temp = temp->next;
}
if (n > length) {
printf("Error: n is greater than the length of the list.");
return -1;
}
int nthFromStart = length - n + 1;
temp = head;
for (int i = 1; i < nthFromStart; i++) {
temp = temp->next;
}
return temp->data;
}
int main() {
int n, secondLast;
printf("Enter the number of nodes: ");
scanf("%d", &n);
struct Node* head = createLinkedList(n);
secondLast = getNthFromEnd(head, 2);
printf("Data of second last node: %d", secondLast);
return 0;
}
```
该代码中包含了两个函数:
- `createLinkedList`:该函数会根据输入的数据创建一个链表,并返回链表的头指针。
- `getNthFromEnd`:该函数会返回链表中倒数第n个节点的数据。
在 `main` 函数中,先调用 `createLinkedList` 创建链表,然后调用 `getNthFromEnd` 函数获取倒数第二个节点的数据,并输出到控制台上。
阅读全文