다음 5개함수 중 가장 잘 쓴 함수라고 생각되는 함수는? 이유는? 틀렸다고 생각되는 함수는? 리스트의 뒤에서 N번째 노드 지운 리스트 리턴하기

w 76.***.207.158

테스트 버전: (메모리리크는 고려안했음. 컴파일이 보이드 타입 리턴 함수라서 안된다니…컴파일러마다 다른 모양이군요. 위5개 함수 모두 잘 실행됨. –내가 코딩한건 아님 ㅋㅋㅋ 살짝 변형한건 있지만 ㅋㅋㅋ 아주 자주 나오는 문제임 — 물론 리턴타입이 리스트 포인터이면 함수콜링을 살짝 바꿔야 하고…int n 은 리스트 끝에서부터의 앞쪽 n번째 노드를 말하고 있으므로 당연히 >=0 이고 전체 리스트의 엘리먼트보다 작거나 같음. 음수를 왜 고려함?)

1번과 5번 함수가 안좋은 가장 큰 이유는,
전혀 필요없는 템포러리 더미 노드를 생성하고 있다는 것이다. 물론 그것이 메모리리크 논란을 일으키고 있지만 메모리리크를 논하기 이전에 이 템포러리 포인터는 전혀 쓰잘데기가 없는데 만들었다. 뭐 그게 꼭 필요했다면 딜리트 한줄 더 늘어난다고 해서 별 대수겠냐만 필요도 없는데 굳이 ….


#include <iostream>
using namespace std;

	
    
class LinkedList {
  public:
	class Node {   // 이 경우는 노드 클래스를 밖으로 안빼내고 그냥 네스트 시켜줌.  난 네스티드 된거 싫더라
	public:
		int data;
		Node* next;

                           Node() : data(0), next(nullptr) {}    // 이 컨스트럭터 첨가해주어도 됨  
		Node(int d)
		{
			data = d;
			next = NULL;
		}
	};
     
	// Function for inserting a node at the beginning
	void push(Node*& head, int data)
	{ 
		Node* new_node = new Node(data);
		new_node->next = head;
		head = new_node;
	}

	// Function to display the nodes in the list.
	void display(Node* head)
	{
		Node* temp = head;
		while (temp != NULL) {
			cout << temp->data << endl;
			temp = temp->next;
		}
	}

	// Function to delete the nth node from the end.
	void removeNthFromEnd(Node* head, int n)
	{ 
		Node* fast = head;
		Node* slow = head;

		for (int i = 0; i < n; i++) {
			fast = fast->next;
		}
		if (fast == NULL) {
			head = head->next;
			return;
		}

		while (fast->next != NULL) {
			fast = fast->next;
			slow = slow->next;
		}
		slow->next = slow->next->next;
		return;
	}
};

int main()
{   
	LinkedList* l = new LinkedList();  
        LinkedList::Node* head = new LinkedList::Node(5) ; 
 
	// Create a list 1->2->3->4->5->NULL
	//l->push(head,5);  // 더블포인터 경우는 l->push(&head,5); 
	l->push(head,4);
	l->push(head,3);
	l->push(head,2);
	l->push(head,1);
	cout << "***** Linked List Before deletion *****"
		<< endl;
	l->display(head);

	cout << "************** Delete nth Node from the End "
			"*****"
		<< endl; 
             l->removeNthFromEnd(head, 2); // 보이드 리턴 타입 함수의 경우 테스트. 더블포인터 경우는 &head 로 변경
    
	cout << "*********** Linked List after Deletion *****"
		<< endl;
	l->display(head);

	return 0;
}