C combine unordered segments with two nodes
To combine two unordered segments in C with two nodes, you can create a struct to represent a node and another struct to represent a segment. Here's an example:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct Segment {
struct Node* head;
struct Node* tail;
} Segment;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// Function to create a new segment with two nodes
Segment* createSegment(int data1, int data2) {
Segment* newSegment = (Segment*)malloc(sizeof(Segment));
newSegment->head = createNode(data1);
newSegment->tail = createNode(data2);
newSegment->head->next = newSegment->tail;
return newSegment;
}
// Function to combine two segments
Segment* combineSegments(Segment* segment1, Segment* segment2) {
segment1->tail->next = segment2->head;
segment1->tail = segment2->tail;
free(segment2);
return segment1;
}
// Function to print a segment
void printSegment(Segment* segment) {
Node* current = segment->head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// Create two segments
Segment* segment1 = createSegment(1, 2);
Segment* segment2 = createSegment(3, 4);
// Combine the segments
Segment* combinedSegment = combineSegments(segment1, segment2);
// Print the combined segment
printSegment(combinedSegment);
// Clean up memory
free(segment1->tail);
free(segment1);
free(combinedSegment);
return 0;
}
In this example, the Node struct represents a node in the segment, with a data member to store the value and a next member to point to the next node. The Segment struct represents a segment, with head and tail members pointing to the first and last nodes of the segment, respectively.
The createNode function creates a new node with the given data, and the createSegment function creates a new segment with two nodes initialized with the given data. The combineSegments function combines two segments by updating the tail of the first segment to point to the head of the second segment, and then freeing the memory occupied by the second segment.
Finally, the printSegment function is used to print the values of the nodes in a segment. In the main function, two segments are created, combined using combineSegments, and then printed using printSegment. Memory is freed at the end to avoid memory leaks
原文地址: https://www.cveoy.top/t/topic/hPqV 著作权归作者所有。请勿转载和采集!