📌  相关文章
📜  找出连接链表的k个连续节点形成的字符串

📅  最后修改于: 2021-09-06 05:08:05             🧑  作者: Mango

给定一个整数K和一个链表,其中每个节点存储一个字符。任务是将链表的每K个连续节点连接起来形成一个单词。最后,打印将这些单词连接起来得到的字符串(空格分隔)。
例子:

方法:这个想法是遍历链表并不断将每个节点上存在的字符添加到到目前为止形成的单词中。跟踪遍历的节点数,当计数等于 k 时,将到目前为止形成的单词添加到结果字符串,将单词重置为空字符串并将计数重置为零。重复此操作,直到没有遍历整个链表。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Structure of a node
struct Node {
    char data;
    Node* next;
};
 
// Function to get a new node
Node* getNode(char data)
{
    // Allocate space
    Node* newNode = new Node;
 
    // Put in data
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
 
// Function to find string formed by joining words
// obtained by joining k consecutive nodes of
// linked list.
string findKWordString(Node* head, int k)
{
    // Stores the final string
    string ans = "";
 
    // Keep track of the number of
    // nodes traversed
    int cnt = 0;
 
    // Stores the word formed by k consecutive
    // nodes of the linked list
    string word = "";
 
    while (head) {
 
        // Check if k nodes are traversed
        // If yes then add the word obtained
        // to the result string
        if (cnt == k) {
            if (ans != "") {
                ans = ans + " ";
            }
 
            ans = ans + word;
            word = "";
            cnt = 0;
        }
 
        // Add the current character to the word
        // formed so far and increase the count
        word = word + string(1, head->data);
        cnt++;
        head = head->next;
    }
 
    // Add the final word to the result
    // Length of the final word can be less than k
    if (ans != " ") {
        ans = ans + " ";
    }
    ans = ans + word;
 
    return ans;
}
 
// Driver code
int main()
{
 
    // Create list: a -> b -> c -> d -> e
    Node* head = getNode('a');
    head->next = getNode('b');
    head->next->next = getNode('c');
    head->next->next->next = getNode('d');
    head->next->next->next->next = getNode('e');
 
    int k = 3;
 
    cout << findKWordString(head, k);
 
    return 0;
}


Java
// Java implementation of the approach
class GFG{
 
// Class of a node
static class Node
{
    char data;
    Node next;
};
 
// Function to get a new node
static Node getNode(char data)
{
     
    // Allocate space
    Node newNode = new Node();
 
    // Put in data
    newNode.data = data;
    newNode.next = null;
    return newNode;
}
 
// Function to find string formed by
// joining words obtained by joining
// k consecutive nodes of linked list.
static String findKWordString(Node head, int k)
{
     
    // Stores the final string
    String ans = "";
 
    // Keep track of the number of
    // nodes traversed
    int cnt = 0;
 
    // Stores the word formed by k consecutive
    // nodes of the linked list
    String word = "";
 
    while (head != null)
    {
 
        // Check if k nodes are traversed
        // if yes then add the word obtained
        // to the result String
        if (cnt == k)
        {
            if (ans != "")
            {
                ans = (ans + " ");
            }
 
            ans = ans + word;
            word = "";
            cnt = 0;
        }
 
        // Add the current character to the word
        // formed so far and increase the count
        word = word + head.data;
        cnt++;
        head = head.next;
    }
 
    // Add the final word to the result
    // Length of the final word can be
    // less than k
    if (ans != " ")
    {
        ans = (ans + " ");
    }
    ans = ans + word;
    return ans;
}
 
// Driver code
public static void main(String[] args)
{
 
    // Create list: a.b.c.d.e
    Node head = getNode('a');
    head.next = getNode('b');
    head.next.next = getNode('c');
    head.next.next.next = getNode('d');
    head.next.next.next.next = getNode('e');
 
    int k = 3;
 
    System.out.print(findKWordString(head, k));
}
}
 
// This code is contributed by GauravRajput1


Python3
# Python3 implementation of the approach
 
# Structure of a node
class Node:
    def __init__(self, d):
        self.data = d
        self.next = None
 
# Function to find formed by joining words
# obtained by joining k consecutive nodes of
# linked list.
def findKWordString(head,k):
     
    # Stores the final
    ans = ""
 
    # Keep track of the number of
    # nodes traversed
    cnt = 0
 
    # Stores the word formed by k consecutive
    # nodes of the linked list
    word = ""
 
    while (head):
 
        # Check if k nodes are traversed
        # If yes then add the word obtained
        # to the result
        if (cnt == k):
            if (ans != ""):
                ans = ans + " "
 
            ans = ans + word
            word = ""
            cnt = 0
 
        # Add the current character to the word
        # formed so far and increase the count
        word = word + head.data
        cnt += 1
        head = head.next
 
    # Add the final word to the result
    # Length of the final word can be less than k
    if (ans != " "):
        ans = ans + " "
    ans = ans + word
 
    return ans
 
# Driver code
if __name__ == '__main__':
 
 
    #Create list: a . b . c . d . e
    head = Node('a')
    head.next = Node('b')
    head.next.next = Node('c')
    head.next.next.next = Node('d')
    head.next.next.next.next = Node('e')
 
    k = 3
 
    print(findKWordString(head, k))
 
# This code is contributed by mohit kumar 29


C#
// C# implementation of the approach
using System;
 
class GFG{
 
// Class of a node
class Node
{
    public char data;
    public Node next;
};
 
// Function to get a new node
static Node getNode(char data)
{
     
    // Allocate space
    Node newNode = new Node();
 
    // Put in data
    newNode.data = data;
    newNode.next = null;
    return newNode;
}
 
// Function to find string formed by
// joining words obtained by joining
// k consecutive nodes of linked list.
static String findKWordString(Node head, int k)
{
     
    // Stores the final string
    String ans = "";
 
    // Keep track of the number
    // of nodes traversed
    int cnt = 0;
 
    // Stores the word formed by k
    // consecutive nodes of the
    // linked list
    String word = "";
 
    while (head != null)
    {
 
        // Check if k nodes are traversed
        // if yes then add the word obtained
        // to the result String
        if (cnt == k)
        {
            if (ans != "")
            {
                ans = (ans + " ");
            }
 
            ans = ans + word;
            word = "";
            cnt = 0;
        }
 
        // Add the current character to the word
        // formed so far and increase the count
        word = word + head.data;
        cnt++;
        head = head.next;
    }
 
    // Add the readonly word to the result
    // Length of the readonly word can be
    // less than k
    if (ans != " ")
    {
        ans = (ans + " ");
    }
    ans = ans + word;
    return ans;
}
 
// Driver code
public static void Main(String[] args)
{
 
    // Create list: a.b.c.d.e
    Node head = getNode('a');
    head.next = getNode('b');
    head.next.next = getNode('c');
    head.next.next.next = getNode('d');
    head.next.next.next.next = getNode('e');
 
    int k = 3;
 
    Console.Write(findKWordString(head, k));
}
}
 
// This code is contributed by gauravrajput1


Javascript


输出:

abc de

时间复杂度: O(N)
辅助空间: O(1)

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live