原文:

给定一个包含n个节点和正整数k的链表,其中k应当小于或等于n。任务是按相反的顺序打印列表的最后k个节点。

示例

input : list: 1->2->3->4->5, k = 2
output : 5 4
input : list: 3->10->6->9->12->2->8, k = 4
output : 8 2 12 9

中讨论的pg电子试玩链接的解决方案使用递归方法。 下面的文章讨论了解决上述问题的三种迭代方法。

方法 1:想法是使用栈数据结构。 推入所有链接的列表节点数据值以堆叠并弹出前k个元素并打印它们。

下面是上述方法的实现:

c

// c   implementation to print the last k nodes 
// of linked list in reverse order 
#include  
using namespace std; 
// structure of a node 
struct node { 
    int data; 
    node* next; 
}; 
// function to get a new node 
node* getnode(int data) 
{ 
    // allocate space 
    node* newnode = new node; 
    // put in data 
    newnode->data = data; 
    newnode->next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
void printlastkrev(node* head, int k) 
{ 
    // if list is empty 
    if (!head) 
        return; 
    // stack to store data value of nodes. 
    stack st; 
    // push data value of nodes to stack 
    while (head) { 
        st.push(head->data); 
        head = head->next; 
    } 
    int cnt = 0; 
    // pop first k elements of stack and 
    // print them. 
    while (cnt < k) { 
        cout << st.top() << " "; 
        st.pop(); 
        cnt  ; 
    } 
} 
// driver code 
int main() 
{ 
    // create list: 1->2->3->4->5 
    node* head = getnode(1); 
    head->next = getnode(2); 
    head->next->next = getnode(3); 
    head->next->next->next = getnode(4); 
    head->next->next->next->next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
    return 0; 
} 

java

// java implementation to print the last k nodes 
// of linked list in reverse order 
import java.util.*; 
class gfg  
{ 
// structure of a node 
static class node 
{ 
    int data; 
    node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // stack to store data value of nodes. 
    stack st = new stack(); 
    // push data value of nodes to stack 
    while (head != null)  
    { 
        st.push(head.data); 
        head = head.next; 
    } 
    int cnt = 0; 
    // pop first k elements of stack and 
    // print them. 
    while (cnt < k)  
    { 
        system.out.print(st.peek()   " "); 
        st.pop(); 
        cnt  ; 
    } 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code is contributed by princiraj1992 

python3

# python3 implementation to print the last k nodes  
# of linked list in reverse order 
import sys 
import math 
# structure of a node  
class node: 
    def __init__(self,data): 
        self.data = data 
        self.next = none
# function to get a new node 
def getnode(data): 
    # allocate space and return new node 
    return node(data) 
# function to print the last k nodes  
# of linked list in reverse order  
def printlastkrev(head,k): 
    # if list is empty 
    if not head: 
        return
    # stack to store data value of nodes. 
    stack = [] 
    # push data value of nodes to stack  
    while(head): 
        stack.append(head.data) 
        head = head.next
    cnt = 0
    # pop first k elements of stack and  
    # print them. 
    while(cnt < k): 
        print("{} ".format(stack[-1]),end="") 
        stack.pop() 
        cnt  = 1
# driver code  
if __name__=='__main__': 
    # create list: 1->2->3->4->5  
    head = getnode(1) 
    head.next = getnode(2) 
    head.next.next = getnode(3) 
    head.next.next.next = getnode(4) 
    head.next.next.next.next = getnode(5) 
    k = 4
    # print the last k nodes  
    printlastkrev(head,k) 
# this code is contributed by vikash kumar 37 

c

// c# implementation to print the last k nodes 
// of linked list in reverse order 
using system; 
using system.collections.generic; 
class gfg  
{ 
// structure of a node 
public class node 
{ 
    public int data; 
    public node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // stack to store data value of nodes. 
    stack st = new stack(); 
    // push data value of nodes to stack 
    while (head != null)  
    { 
        st.push(head.data); 
        head = head.next; 
    } 
    int cnt = 0; 
    // pop first k elements of stack and 
    // print them. 
    while (cnt < k)  
    { 
        console.write(st.peek()   " "); 
        st.pop(); 
        cnt  ; 
    } 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code contributed by rajput-ji 

输出

5 4 3 2

时间复杂度o(n)

辅助空间o(n)

上述方法的辅助空间可以减小为o(k)。 这个想法是使用两个指针。 将第一个指针移到列表的开头,然后将第二个指针移到第k个节点。 然后使用本文讨论的方法从头开始查找第k个节点:从的末尾查找第k个节点。 从末端找到第k个节点后,推入栈中的所有其余节点。 从栈中逐一弹出所有元素并进行打印。

以下是上述有效方法的实现:

c

// c   implementation to print the last k nodes 
// of linked list in reverse order 
#include  
using namespace std; 
// structure of a node 
struct node { 
    int data; 
    node* next; 
}; 
// function to get a new node 
node* getnode(int data) 
{ 
    // allocate space 
    node* newnode = new node; 
    // put in data 
    newnode->data = data; 
    newnode->next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
void printlastkrev(node* head, int k) 
{ 
    // if list is empty 
    if (!head) 
        return; 
    // stack to store data value of nodes. 
    stack st; 
    // declare two pointers. 
    node *first = head, *sec = head; 
    int cnt = 0; 
    // move second pointer to kth node. 
    while (cnt < k) { 
        sec = sec->next; 
        cnt  ; 
    } 
    // move first pointer to kth node from end 
    while (sec) { 
        first = first->next; 
        sec = sec->next; 
    } 
    // push last k nodes in stack 
    while (first) { 
        st.push(first->data); 
        first = first->next; 
    } 
    // last k nodes are reversed when pushed 
    // in stack. pop all k elements of stack 
    // and print them. 
    while (!st.empty()) { 
        cout << st.top() << " "; 
        st.pop(); 
    } 
} 
// driver code 
int main() 
{ 
    // create list: 1->2->3->4->5 
    node* head = getnode(1); 
    head->next = getnode(2); 
    head->next->next = getnode(3); 
    head->next->next->next = getnode(4); 
    head->next->next->next->next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
    return 0; 
} 

java

// java implementation to print  
// the last k nodes of linked list 
// in reverse order 
import java.util.*; 
class gfg 
{ 
// structure of a node 
static class node  
{ 
    int data; 
    node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // stack to store data value of nodes. 
    stack st = new stack(); 
    // declare two pointers. 
    node first = head, sec = head; 
    int cnt = 0; 
    // move second pointer to kth node. 
    while (cnt < k)  
    { 
        sec = sec.next; 
        cnt  ; 
    } 
    // move first pointer to kth node from end 
    while (sec != null) 
    { 
        first = first.next; 
        sec = sec.next; 
    } 
    // push last k nodes in stack 
    while (first != null) 
    { 
        st.push(first.data); 
        first = first.next; 
    } 
    // last k nodes are reversed when pushed 
    // in stack. pop all k elements of stack 
    // and print them. 
    while (!st.empty()) 
    { 
        system.out.print(st.peek()   " "); 
        st.pop(); 
    } 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code is contributed by princi singh 

python

# python implementation to print the last k nodes 
# of linked list in reverse order 
# node class  
class node: 
    # function to initialise the node object  
    def __init__(self, data):  
        self.data = data # assign data  
        self.next = none
# function to get a new node 
def getnode(data): 
    # allocate space 
    newnode = node(0) 
    # put in data 
    newnode.data = data 
    newnode.next = none
    return newnode 
# function to print the last k nodes 
# of linked list in reverse order 
def printlastkrev( head, k): 
    # if list is empty 
    if (head == none): 
        return
    # stack to store data value of nodes. 
    st = [] 
    # declare two pointers. 
    first = head 
    sec = head 
    cnt = 0
    # move second pointer to kth node. 
    while (cnt < k) : 
        sec = sec.next
        cnt = cnt   1
    # move first pointer to kth node from end 
    while (sec != none):  
        first = first.next
        sec = sec.next
    # push last k nodes in stack 
    while (first != none):  
        st.append(first.data) 
        first = first.next
    # last k nodes are reversed when pushed 
    # in stack. pop all k elements of stack 
    # and print them. 
    while (len(st)):  
        print( st[-1], end= " ") 
        st.pop() 
# driver code 
# create list: 1.2.3.4.5 
head = getnode(1) 
head.next = getnode(2) 
head.next.next = getnode(3) 
head.next.next.next = getnode(4) 
head.next.next.next.next = getnode(5) 
k = 4
# print the last k nodes 
printlastkrev(head, k) 
# this code is contributed by arnab kundu 

c

// c# implementation to print  
// the last k nodes of linked list 
// in reverse order 
using system; 
using system.collections.generic;  
class gfg 
{ 
// structure of a node 
class node  
{ 
    public int data; 
    public node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // stack to store data value of nodes. 
    stack st = new stack(); 
    // declare two pointers. 
    node first = head, sec = head; 
    int cnt = 0; 
    // move second pointer to kth node. 
    while (cnt < k)  
    { 
        sec = sec.next; 
        cnt  ; 
    } 
    // move first pointer to kth node from end 
    while (sec != null) 
    { 
        first = first.next; 
        sec = sec.next; 
    } 
    // push last k nodes in stack 
    while (first != null) 
    { 
        st.push(first.data); 
        first = first.next; 
    } 
    // last k nodes are reversed when pushed 
    // in stack. pop all k elements of stack 
    // and print them. 
    while (st.count != 0) 
    { 
        console.write(st.peek()   " "); 
        st.pop(); 
    } 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code is contributed by 29ajaykumar 

输出

5 4 3 2

时间复杂度o(n)

辅助空间o(k)

方法 2

  • 计算链表中的节点数。

  • 声明一个数组,并以节点数作为其大小。

  • 从数组末尾开始存储链表的节点值,即反向存储。

  • 从数组开始打印k个值。

c

#include   
using namespace std;  
// structure of a node  
struct node {  
    int data;  
    node* next;  
};  
// function to get a new node  
node* getnode(int data){  
    // allocate space  
    node* newnode = new node;  
    // put in data  
    newnode->data = data;  
    newnode->next = null;  
    return newnode;  
}  
// function to print the last k nodes  
// of linked list in reverse order  
void printlastkrev(node* head,  
                     int& count, int k) { 
    struct node* cur = head; 
    while(cur != null){ 
        count  ; 
        cur = cur->next; 
    } 
    int arr[count], temp = count; 
    cur = head; 
    while(cur != null){ 
        arr[--temp] = cur->data; 
        cur = cur->next; 
    } 
    for(int i = 0; i < k; i  ) 
        cout << arr[i] << " "; 
}  
  // 
// driver code  
int main()  
{  
    // create list: 1->2->3->4->5  
    node* head = getnode(1);  
    head->next = getnode(2);  
    head->next->next = getnode(3);  
    head->next->next->next = getnode(4);  
    head->next->next->next->next = getnode(5); 
    head->next->next->next->next->next = getnode(10); 
    int k = 4, count = 0;  
    // print the last k nodes  
    printlastkrev(head, count, k);  
    return 0;  
}  

java

// java code implementation for above approach 
class gfg  
{  
// structure of a node  
static class node 
{  
    int data;  
    node next;  
};  
// function to get a new node  
static node getnode(int data) 
{  
    // allocate space  
    node newnode = new node();  
    // put in data  
    newnode.data = data;  
    newnode.next = null;  
    return newnode;  
}  
// function to print the last k nodes  
// of linked list in reverse order  
static void printlastkrev(node head,  
                          int count, int k)  
{ 
    node cur = head; 
    while(cur != null) 
    { 
        count  ; 
        cur = cur.next; 
    } 
    int []arr = new int[count]; 
    int temp = count; 
    cur = head; 
    while(cur != null) 
    { 
        arr[--temp] = cur.data; 
        cur = cur.next; 
    } 
    for(int i = 0; i < k; i  ) 
        system.out.print(arr[i]   " "); 
}  
// driver code  
public static void main(string[] args)  
{ 
    // create list: 1.2.3.4.5  
    node head = getnode(1);  
    head.next = getnode(2);  
    head.next.next = getnode(3);  
    head.next.next.next = getnode(4);  
    head.next.next.next.next = getnode(5); 
    head.next.next.next.next.next = getnode(10); 
    int k = 4, count = 0;  
    // print the last k nodes  
    printlastkrev(head, count, k);  
} 
} 
// this code is contributed by 29ajaykumar 

c

// c# code implementation for above approach 
using system; 
class gfg  
{  
// structure of a node  
class node 
{  
    public int data;  
    public node next;  
};  
// function to get a new node  
static node getnode(int data) 
{  
    // allocate space  
    node newnode = new node();  
    // put in data  
    newnode.data = data;  
    newnode.next = null;  
    return newnode;  
}  
// function to print the last k nodes  
// of linked list in reverse order  
static void printlastkrev(node head,  
                          int count, int k)  
{ 
    node cur = head; 
    while(cur != null) 
    { 
        count  ; 
        cur = cur.next; 
    } 
    int []arr = new int[count]; 
    int temp = count; 
    cur = head; 
    while(cur != null) 
    { 
        arr[--temp] = cur.data; 
        cur = cur.next; 
    } 
    for(int i = 0; i < k; i  ) 
        console.write(arr[i]   " "); 
}  
// driver code  
public static void main(string[] args)  
{ 
    // create list: 1.2.3.4.5  
    node head = getnode(1);  
    head.next = getnode(2);  
    head.next.next = getnode(3);  
    head.next.next.next = getnode(4);  
    head.next.next.next.next = getnode(5); 
    head.next.next.next.next.next = getnode(10); 
    int k = 4, count = 0;  
    // print the last k nodes  
    printlastkrev(head, count, k);  
} 
} 
// this code is contributed by princiraj1992 

输出

10 5 4 3

时间复杂度o(n)

辅助空间o(n)

方法 3:想法是首先迭代地反向链表,如以下文章所述:。 反转后,打印反转列表的前k个节点。 打印后,通过再次反转列表来恢复列表。

下面是上述方法的实现:

c

// c   implementation to print the last k nodes 
// of linked list in reverse order 
#include  
using namespace std; 
// structure of a node 
struct node { 
    int data; 
    node* next; 
}; 
// function to get a new node 
node* getnode(int data) 
{ 
    // allocate space 
    node* newnode = new node; 
    // put in data 
    newnode->data = data; 
    newnode->next = null; 
    return newnode; 
} 
// function to reverse the linked list. 
node* reversell(node* head) 
{ 
    if (!head || !head->next) 
        return head; 
    node *prev = null, *next = null, *curr = head; 
    while (curr) { 
        next = curr->next; 
        curr->next = prev; 
        prev = curr; 
        curr = next; 
    } 
    return prev; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
void printlastkrev(node* head, int k) 
{ 
    // if list is empty 
    if (!head) 
        return; 
    // reverse linked list. 
    head = reversell(head); 
    node* curr = head; 
    int cnt = 0; 
    // print first k nodes of linked list. 
    while (cnt < k) { 
        cout << curr->data << " "; 
        cnt  ; 
        curr = curr->next; 
    } 
    // restore the list. 
    head = reversell(head); 
} 
// driver code 
int main() 
{ 
    // create list: 1->2->3->4->5 
    node* head = getnode(1); 
    head->next = getnode(2); 
    head->next->next = getnode(3); 
    head->next->next->next = getnode(4); 
    head->next->next->next->next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
    return 0; 
} 

java

// java implementation to print the last k nodes 
// of linked list in reverse order 
import java.util.*; 
class gfg 
{ 
// structure of a node 
static class node  
{ 
    int data; 
    node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to reverse the linked list. 
static node reversell(node head) 
{ 
    if (head == null || head.next == null) 
        return head; 
    node prev = null, next = null, curr = head; 
    while (curr != null) 
    { 
        next = curr.next; 
        curr.next = prev; 
        prev = curr; 
        curr = next; 
    } 
    return prev; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // reverse linked list. 
    head = reversell(head); 
    node curr = head; 
    int cnt = 0; 
    // print first k nodes of linked list. 
    while (cnt < k)  
    { 
        system.out.print(curr.data   " "); 
        cnt  ; 
        curr = curr.next; 
    } 
    // restore the list. 
    head = reversell(head); 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code is contributed by 29ajaykumar 

c

// c# implementation to print the last k nodes 
// of linked list in reverse order 
using system; 
class gfg 
{ 
// structure of a node 
public class node  
{ 
    public int data; 
    public node next; 
}; 
// function to get a new node 
static node getnode(int data) 
{ 
    // allocate space 
    node newnode = new node(); 
    // put in data 
    newnode.data = data; 
    newnode.next = null; 
    return newnode; 
} 
// function to reverse the linked list. 
static node reversell(node head) 
{ 
    if (head == null || head.next == null) 
        return head; 
    node prev = null, next = null, curr = head; 
    while (curr != null) 
    { 
        next = curr.next; 
        curr.next = prev; 
        prev = curr; 
        curr = next; 
    } 
    return prev; 
} 
// function to print the last k nodes 
// of linked list in reverse order 
static void printlastkrev(node head, int k) 
{ 
    // if list is empty 
    if (head == null) 
        return; 
    // reverse linked list. 
    head = reversell(head); 
    node curr = head; 
    int cnt = 0; 
    // print first k nodes of linked list. 
    while (cnt < k)  
    { 
        console.write(curr.data   " "); 
        cnt  ; 
        curr = curr.next; 
    } 
    // restore the list. 
    head = reversell(head); 
} 
// driver code 
public static void main(string[] args) 
{ 
    // create list: 1->2->3->4->5 
    node head = getnode(1); 
    head.next = getnode(2); 
    head.next.next = getnode(3); 
    head.next.next.next = getnode(4); 
    head.next.next.next.next = getnode(5); 
    int k = 4; 
    // print the last k nodes 
    printlastkrev(head, k); 
} 
} 
// this code is contributed by princi singh 

输出

5 4 3 2

时间复杂度o(n)

辅助空间o(1)



如果您喜欢 geeksforgeeks 并希望做出贡献,则还可以使用 tribution.geeksforgeeks.org 撰写文章,或将您的文章邮寄至 tribution@geeksforgeeks.org。 查看您的文章出现在 geeksforgeeks pg电子试玩链接主页上,并帮助其他 geeks。

如果您发现任何不正确的地方,请单击下面的“改进文章”按钮,以改进本文。