單鏈表,弄清楚可stl中list的區別
ListNode的結構
struct ListNode {
int val; //當前結點的值
ListNode *next; //指向下一個結點的指針
ListNode(int x) : val(x), next(NULL) {} //初始化當前結點值爲x,指針爲空
};
如何向ListNode中插入新的結點:從鍵盤輸入
ListNode* temp1 = new Solution::ListNode(0); //創建新元素,
ListNode* l1 = temp1; //最後的結果l1指向temp1,這樣可以獲取temp所接收的全部元素,而temp的指針由於每次都往下移,所以每次都更新
while ((c = getchar()) != '\n') //以空格區分各個結點的值
{
if (c != ' ')
{
ungetc(c, stdin); //把不是空格的字符丟回去
cin >> num;
Solution::ListNode* newnode = new Solution::ListNode(0);
newnode->val = num;//創建新的結點存放鍵盤中讀入的值
newnode->next = NULL;
temp2->next = newnode;//並將其賦值給temp2
temp2 = newnode; //此處也可以寫成 temp2=temp2->next,使指針指向下一個,以待接收新元素
}
}
逆序輸出所有元素
void Solution::reversePrintListNode(ListNode* head)
{
if (head == nullptr) return;
cout << head->val; //順序輸出
reversePrintListNode(head->next);
cout << head->val; //逆序輸出
}